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
maincalls 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.18Step-by-step explanation
main.gobelongs to packagemain, the package used to create an executable.import "example.com/shop/pricing"imports thepricingpackage.pricing.Price(100)calls the exportedPricefunction.Pricecalculates100 + 100*0.18, producing118.pricing.TaxRateaccesses the exported constant.discountandDiscountare 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
14Step-by-step explanation
go.moddeclares the module path asexample.com/shop.The import path
example.com/shop/mathutilmeans themathutilpackage inside that module.Double(7)receives7.The function returns
7 * 2, which is14.No external dependency is required because
mathutilbelongs 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.modrecords its dependencies.
Chapter 23 — Standard Library Essentials
Question
Given below is a code snippet that:
Demonstrates
fmt.Sprintffor 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-3Step-by-step explanation
name := "go"creates a string.count := 3creates an integer.strings.ToUpper(name)returns"GO".strconv.Itoa(count)converts3into the string"3".fmt.Sprintf("%s-%s", ...)combines the two strings with a hyphen.messagebecomes"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 GoStep-by-step explanation
filename := "message.txt"stores the file name.[]byte("Hello Go")converts the string into bytes.os.WriteFilecreates or replaces the file and writes the bytes.0644is the file permission mode.os.ReadFilereads the file contents into a byte slice.string(data)converts the bytes back into a string.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 30Step-by-step explanation
Useris a struct withNameandAgefields.`json:"name"`is a struct tag telling the JSON package to use"name"as the JSON key.json.Marshal(user)converts the Go struct into JSON bytes.string(data)converts those bytes into a printable string.json.Unmarshalreads JSON bytes and fills thedecodedstruct.&decodedgives the function the address of the struct so it can modify it.decoded.Nameanddecoded.Agecontain"Anita"and30.
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/jsonpackage 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
2h0m0sStep-by-step explanation
time.Datecreates a time value for January 10, 2026, at 09:30 UTC.time.UTCspecifies the UTC time zone.2 * time.Hourcreates a duration of two hours.start.Add(...)returns a new time two hours later.Format("2006-01-02 15:04")formats the time using Go's reference layout.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
FindStringdiffers fromMatchString.
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
123Step-by-step explanation
regexp.MustCompilecompiles the regular expression.`\d+`is a raw string containing the pattern.\dmatches a digit.+means one or more repetitions.MatchString(text)checks whether the text contains a matching sequence.FindString(text)returns the first matching substring.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.comStep-by-step explanation
http.NewRequestcreates an HTTP request."GET"is the HTTP method, which indicates that the client wants to retrieve a resource."https://example.com"is the URL.nilmeans the request has no body.req.Methodreturns"GET".req.URL.Hostreturns"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
trueStep-by-step explanation
http.Getsends an HTTP GET request.If the request fails,
erris notnil.defer resp.Body.Close()schedules the response body to close whenmainreturns.io.ReadAllreads the response body into a byte slice.resp.StatusCodecontains the HTTP status code.len(body) > 0checks whether the response contains at least one byte.The example website normally returns status
200and 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, /goStep-by-step explanation
hellois an HTTP handler function.http.ResponseWriteris used to send a response to the client.*http.Requestcontains information about the incoming request.httptest.NewRequestcreates a test request for/go.httptest.NewRecordercreates a test response writer that records the handler's output.hello(rec, req)runs the handler.r.URL.Pathis"/go".fmt.Fprintwrites"Hello, /go"to the response body.rec.Codeis200, 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.