GO 21 - 30

Chapter 21 — Packages & Visibility

Question

Given below is a code snippet that:

  • Demonstrates how a package is declared and imported.

  • Demonstrates exported and unexported identifiers.

  • Demonstrates how main calls a function from another package.

  • Demonstrates how package visibility works.

What should be the output of the following code?

Assume these files are inside the same Go module, and example.com/shop is the module path.

// file: main.go
package main

import (
	"fmt"
	"example.com/shop/pricing"
)

func main() {
	fmt.Println(pricing.Price(100))
	fmt.Println(pricing.TaxRate)
}
// file: pricing/pricing.go
package pricing

const TaxRate = 0.18

const discount = 0.10

func Price(amount float64) float64 {
	return amount + amount*TaxRate
}

func Discount(amount float64) float64 {
	return amount - amount*discount
}

Answer

118
0.18

Step-by-step explanation

  1. main.go belongs to package main, the package used to create an executable.

  2. import "example.com/shop/pricing" imports the pricing package.

  3. pricing.Price(100) calls the exported Price function.

  4. Price calculates 100 + 100*0.18, producing 118.

  5. pricing.TaxRate accesses the exported constant.

  6. discount and Discount are not used, so they do not affect the output.

How to read the important code

pricing.Price(100)

"pricing dot Price, open parenthesis, one hundred, close parenthesis."

const TaxRate = 0.18

"const TaxRate equals zero point eighteen."

Key takeaway

An identifier beginning with an uppercase letter is exported and can be accessed from another package; lowercase identifiers are not.


Chapter 22 — Go Modules & Dependency Management

Question

Given below is a code snippet that:

  • Demonstrates a module path.

  • Demonstrates importing a package from the same module.

  • Demonstrates how Go resolves an imported package.

  • Demonstrates a dependency-free module.

What should be the output of the following code?

Assume the module is initialized with go mod init example.com/shop.

// file: go.mod
module example.com/shop

go 1.25
// file: main.go
package main

import (
	"fmt"
	"example.com/shop/mathutil"
)

func main() {
	fmt.Println(mathutil.Double(7))
}
// file: mathutil/mathutil.go
package mathutil

func Double(n int) int {
	return n * 2
}

Answer

14

Step-by-step explanation

  1. go.mod declares the module path as example.com/shop.

  2. The import path example.com/shop/mathutil means the mathutil package inside that module.

  3. Double(7) receives 7.

  4. The function returns 7 * 2, which is 14.

  5. No external dependency is required because mathutil belongs to the same module.

How to read the important code

module example.com/shop

"module example dot com slash shop."

import "example.com/shop/mathutil"

"import example dot com slash shop slash mathutil."

Key takeaway

A Go module defines the root import path of your project, and go.mod records its dependencies.


Chapter 23 — Standard Library Essentials

Question

Given below is a code snippet that:

  • Demonstrates fmt.Sprintf for formatted strings.

  • Demonstrates strings.ToUpper.

  • Demonstrates strconv.Itoa.

  • Demonstrates how standard-library functions can be combined.

What should be the output of the following code?

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	name := "go"
	count := 3

	message := fmt.Sprintf("%s-%s", strings.ToUpper(name), strconv.Itoa(count))

	fmt.Println(message)
}

Answer

GO-3

Step-by-step explanation

  1. name := "go" creates a string.

  2. count := 3 creates an integer.

  3. strings.ToUpper(name) returns "GO".

  4. strconv.Itoa(count) converts 3 into the string "3".

  5. fmt.Sprintf("%s-%s", ...) combines the two strings with a hyphen.

  6. message becomes "GO-3".

How to read the important code

fmt.Sprintf("%s-%s", strings.ToUpper(name), strconv.Itoa(count))

"fmt dot Sprintf, open parenthesis, percent s hyphen percent s, comma, strings dot ToUpper, open parenthesis, name, close parenthesis, comma, strconv dot Itoa, open parenthesis, count, close parenthesis, close parenthesis."

Key takeaway

Go's standard library provides ready-made tools for common tasks such as formatting, string manipulation, and type conversion.


Chapter 24 — File Handling & I/O

Question

Given below is a code snippet that:

  • Demonstrates writing text to a file.

  • Demonstrates reading the file back.

  • Demonstrates converting between strings and byte slices.

  • Demonstrates basic file I/O using os.

What should be the output of the following code?

package main

import (
	"fmt"
	"os"
)

func main() {
	filename := "message.txt"

	err := os.WriteFile(filename, []byte("Hello Go"), 0644)
	if err != nil {
		fmt.Println("write error")
		return
	}

	data, err := os.ReadFile(filename)
	if err != nil {
		fmt.Println("read error")
		return
	}

	fmt.Println(string(data))

	os.Remove(filename)
}

Answer

Hello Go

Step-by-step explanation

  1. filename := "message.txt" stores the file name.

  2. []byte("Hello Go") converts the string into bytes.

  3. os.WriteFile creates or replaces the file and writes the bytes.

  4. 0644 is the file permission mode.

  5. os.ReadFile reads the file contents into a byte slice.

  6. string(data) converts the bytes back into a string.

  7. os.Remove(filename) deletes the temporary file.

How to read the important code

data, err := os.ReadFile(filename)

"data comma err colon equals os dot ReadFile, open parenthesis, filename, close parenthesis."

if err != nil {

"if err is not equal to nil, open curly brace."

Key takeaway

File operations commonly return both data and an error, so always check the error before using the result.


Chapter 25 — JSON & Serialization

Question

Given below is a code snippet that:

  • Demonstrates converting a Go struct into JSON.

  • Demonstrates converting JSON back into a Go struct.

  • Demonstrates JSON struct tags.

  • Demonstrates the difference between Go field names and JSON field names.

What should be the output of the following code?

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	user := User{Name: "Ravi", Age: 25}

	data, _ := json.Marshal(user)
	fmt.Println(string(data))

	var decoded User
	json.Unmarshal([]byte(`{"name":"Anita","age":30}`), &decoded)

	fmt.Println(decoded.Name, decoded.Age)
}

Answer

{"name":"Ravi","age":25}
Anita 30

Step-by-step explanation

  1. User is a struct with Name and Age fields.

  2. `json:"name"` is a struct tag telling the JSON package to use "name" as the JSON key.

  3. json.Marshal(user) converts the Go struct into JSON bytes.

  4. string(data) converts those bytes into a printable string.

  5. json.Unmarshal reads JSON bytes and fills the decoded struct.

  6. &decoded gives the function the address of the struct so it can modify it.

  7. decoded.Name and decoded.Age contain "Anita" and 30.

How to read the important code

data, _ := json.Marshal(user)

"data comma underscore colon equals json dot Marshal, open parenthesis, user, close parenthesis."

json.Unmarshal([]byte(`{"name":"Anita","age":30}`), &decoded)

"json dot Unmarshal, open parenthesis, square bracket byte, open parenthesis, raw string, close parenthesis, comma, ampersand decoded, close parenthesis."

Key takeaway

JSON is a common format for exchanging data, and Go's encoding/json package converts between JSON and structs.


Chapter 26 — Time, Dates & Formatting

Question

Given below is a code snippet that:

  • Demonstrates creating a time value.

  • Demonstrates adding a duration.

  • Demonstrates formatting a time.

  • Demonstrates how Go's time layout works.

What should be the output of the following code?

package main

import (
	"fmt"
	"time"
)

func main() {
	start := time.Date(2026, time.January, 10, 9, 30, 0, 0, time.UTC)
	end := start.Add(2 * time.Hour)

	fmt.Println(start.Format("2006-01-02 15:04"))
	fmt.Println(end.Format("2006-01-02 15:04"))
	fmt.Println(end.Sub(start))
}

Answer

2026-01-10 09:30
2026-01-10 11:30
2h0m0s

Step-by-step explanation

  1. time.Date creates a time value for January 10, 2026, at 09:30 UTC.

  2. time.UTC specifies the UTC time zone.

  3. 2 * time.Hour creates a duration of two hours.

  4. start.Add(...) returns a new time two hours later.

  5. Format("2006-01-02 15:04") formats the time using Go's reference layout.

  6. end.Sub(start) calculates the duration between the two times.

How to read the important code

end := start.Add(2 * time.Hour)

"end colon equals start dot Add, open parenthesis, two times time dot Hour, close parenthesis."

start.Format("2006-01-02 15:04")

"start dot Format, open parenthesis, double quote two thousand six dash zero one dash zero two, space, one five colon zero four, double quote, close parenthesis."

Key takeaway

Go formats time using the special reference layout 2006-01-02 15:04:05.


Chapter 27 — Regular Expressions

Question

Given below is a code snippet that:

  • Demonstrates compiling a regular expression.

  • Demonstrates matching a string.

  • Demonstrates extracting a substring.

  • Demonstrates how FindString differs from MatchString.

What should be the output of the following code?

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\d+`)

	text := "Order 123 is ready"

	fmt.Println(re.MatchString(text))
	fmt.Println(re.FindString(text))
}

Answer

true
123

Step-by-step explanation

  1. regexp.MustCompile compiles the regular expression.

  2. `\d+` is a raw string containing the pattern.

  3. \d matches a digit.

  4. + means one or more repetitions.

  5. MatchString(text) checks whether the text contains a matching sequence.

  6. FindString(text) returns the first matching substring.

  7. The first number in the text is "123".

How to read the important code

re := regexp.MustCompile(`\d+`)

"re colon equals regexp dot MustCompile, open parenthesis, raw string backslash d plus, close parenthesis."

fmt.Println(re.FindString(text))

"fmt dot Println, open parenthesis, re dot FindString, open parenthesis, text, close parenthesis, close parenthesis."

Key takeaway

Regular expressions are patterns used to search, validate, or extract text.


Chapter 28 — HTTP Fundamentals

Question

Given below is a code snippet that:

  • Demonstrates creating an HTTP request.

  • Demonstrates the difference between an HTTP method and URL.

  • Demonstrates reading the response status.

  • Demonstrates closing the response body.

What should be the output of the following code?

package main

import (
	"fmt"
	"net/http"
)

func main() {
	req, _ := http.NewRequest("GET", "https://example.com", nil)

	fmt.Println(req.Method)
	fmt.Println(req.URL.Host)
}

Answer

GET
example.com

Step-by-step explanation

  1. http.NewRequest creates an HTTP request.

  2. "GET" is the HTTP method, which indicates that the client wants to retrieve a resource.

  3. "https://example.com" is the URL.

  4. nil means the request has no body.

  5. req.Method returns "GET".

  6. req.URL.Host returns "example.com".

How to read the important code

req, _ := http.NewRequest("GET", "https://example.com", nil)

"req comma underscore colon equals http dot NewRequest, open parenthesis, double quote GET double quote, comma, double quote https colon slash slash example dot com double quote, comma, nil, close parenthesis."

Key takeaway

An HTTP request describes what a client wants to do, while an HTTP response contains the server's result.


Chapter 29 — HTTP Clients

Question

Given below is a code snippet that:

  • Demonstrates sending an HTTP request.

  • Demonstrates reading the response body.

  • Demonstrates checking an HTTP status.

  • Demonstrates the importance of closing the response body.

What should be the output of the following code?

package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	resp, err := http.Get("https://example.com")
	if err != nil {
		fmt.Println("request failed")
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read failed")
		return
	}

	fmt.Println(resp.StatusCode)
	fmt.Println(len(body) > 0)
}

Answer

200
true

Step-by-step explanation

  1. http.Get sends an HTTP GET request.

  2. If the request fails, err is not nil.

  3. defer resp.Body.Close() schedules the response body to close when main returns.

  4. io.ReadAll reads the response body into a byte slice.

  5. resp.StatusCode contains the HTTP status code.

  6. len(body) > 0 checks whether the response contains at least one byte.

  7. The example website normally returns status 200 and a non-empty body.

How to read the important code

defer resp.Body.Close()

"defer resp dot Body dot Close, open parenthesis, close parenthesis."

body, err := io.ReadAll(resp.Body)

"body comma err colon equals io dot ReadAll, open parenthesis, resp dot Body, close parenthesis."

Key takeaway

Always check HTTP errors and close response bodies after receiving them.


Chapter 30 — HTTP Servers & Handlers

Question

Given below is a code snippet that:

  • Demonstrates an HTTP handler.

  • Demonstrates writing a response.

  • Demonstrates starting an HTTP server.

  • Demonstrates the relationship between a request and a response.

What should be the output of the following code?

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, "+r.URL.Path)
}

func main() {
	req := httptest.NewRequest("GET", "/go", nil)
	rec := httptest.NewRecorder()

	hello(rec, req)

	fmt.Println(rec.Code)
	fmt.Println(rec.Body.String())
}

Answer

200
Hello, /go

Step-by-step explanation

  1. hello is an HTTP handler function.

  2. http.ResponseWriter is used to send a response to the client.

  3. *http.Request contains information about the incoming request.

  4. httptest.NewRequest creates a test request for /go.

  5. httptest.NewRecorder creates a test response writer that records the handler's output.

  6. hello(rec, req) runs the handler.

  7. r.URL.Path is "/go".

  8. fmt.Fprint writes "Hello, /go" to the response body.

  9. rec.Code is 200, the default successful HTTP status.

How to read the important code

func hello(w http.ResponseWriter, r *http.Request)

"func hello, open parenthesis, w http dot ResponseWriter, comma, r asterisk http dot Request, close parenthesis."

fmt.Fprint(w, "Hello, "+r.URL.Path)

"fmt dot Fprint, open parenthesis, w, comma, double quote Hello comma space double quote, plus, r dot URL dot Path, close parenthesis."

Key takeaway

An HTTP handler receives a request and writes a response, forming the basic building block of a Go web server.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.