Irbisa · Cheatsheet
Go Basics
Syntax, zero values, constants and iota, control flow, defer and closures
What is Go, why was it created, and what are its main strengths and weaknesses?
Which familiar features does Go leave out on purpose (ternary operator,
while, inheritance, exceptions, overloading) and what does it use instead?What is a package in Go, how do you import one, and what makes a name exported?
// store/store.go, in module example.com/apppackage store type Row struct { ID int // exported: visible to other packages and to encoding/json name string // unexported: visible only inside package store…What is the difference between
go run,go buildandgo install?What are the ways to declare a variable in Go, and where can you use
:=?var build = "dev" // package level: `build := "dev"` here is a syntax error func load(path string) error { var rows []Row // no value yet: the zero value (a nil slice) is what we want var id uint64 = 7 // := would have inferred int…What is a zero value in Go, and what is it for numbers, strings, pointers, slices, maps, channels and structs?
type Server struct { Addr string // "" Port int // 0 mu sync.Mutex // ready to use, no constructor buf bytes.Buffer // same tags []string // nil…What are constants and
iotain Go, and how do you write an enum?type State uint8 const ( StateUnknown State = iota // 0, also the zero value of State StatePending // 1: the line repeats `State = iota` StateRunning // 2…What size is
intin Go, and what happens on integer overflow and on division by zero?func main() { defer func() { fmt.Println("recovered:", recover()) }() fmt.Println(strconv.IntSize) // 64 on amd64 and arm64 var a int8 = 127…How does type conversion work in Go, and why is there no implicit conversion between numeric types?
done, total := 3, 4fmt.Println(done / total * 100) // 0: integer division firstfmt.Println(float64(done/total) * 100) // 0: converted too latefmt.Println(float64(done) / float64(total) * 100) // 75 v, f, n := 300, 3.9, -1…What forms does the
forloop take in Go, and what canrangeiterate over?for i := 0; i < 3; i++ { // three-clause fmt.Print(i)} for rows.Next() { // condition only: Go's while scan(rows)…What does this loop print, and how do you make the
breakstop the loop?jobs := []string{"a", "stop", "b"}for _, j := range jobs { switch j { case "stop": fmt.Println("stopping") break default: fmt.Println("run", j) }}How do multiple return values work in Go, and what is the blank identifier
_used for?func divmod(a, b int) (int, int, error) { if b == 0 { return 0, 0, errors.New("division by zero") } return a / b, a % b, nil}…What is a variadic function, and how do you pass a slice to one?
func sum(xs ...int) int { total := 0 for _, x := range xs { total += x } return total…How are arguments passed to functions in Go, and when should you pass a pointer instead of a value?
type Config struct { Addr string Timeout time.Duration} func setTimeoutCopy(c Config) { // wrong: changes a copy…What is the difference between
makeandnew?p := new(int) // *int pointing at 0u := &User{Name: "ada"} // *User with fields set: the usual choicem := make(map[string]int) // ready for writess := make([]int, 0, 100) // len 0, cap 100ch := make(chan int, 10) // buffered channel…How does
deferwork: when do deferred calls run, in what order, and when are their arguments evaluated?func countdown() { for i := 0; i < 3; i++ { defer fmt.Print(i, " ") // i is evaluated now, the call runs at return }} // prints 2 1 0…What is the difference between
fmt.Println,fmt.Printfandfmt.Sprintf, and what do%v,%+v,%#v,%Tand%qprint?type User struct { ID int Name string} func main() {…This helper tries several URLs and logs every failed one, yet returns
nilwhen all of them fail. Why, and why is there no compiler warning?func fetch(urls []string) error { var err error for _, u := range urls { if resp, err := http.Get(u); err != nil { log.Printf("attempt %s: %v", u, err) } else { resp.Body.Close() return nil } } return err}Find the bug:
lastNreturns the right items for smalln, but panics withindex out of rangewhennequalslen(xs).func lastN(xs []int, n uint) []int { var out []int for i := uint(len(xs)) - 1; i >= uint(len(xs))-n; i-- { out = append(out, xs[i]) } return out}What does
f()return, and what would it return if the result were not named?func f() (n int) { defer func() { n *= 2 }() n = 1 return n + 2}Find the bug:
hashAllpasses its tests but fails in production on large directories withtoo many open files.func hashAll(paths []string) (map[string]string, error) { sums := make(map[string]string, len(paths)) for _, p := range paths { f, err := os.Open(p) if err != nil { return nil, err } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { return nil, err } sums[p] = hex.EncodeToString(h.Sum(nil)) } return sums, nil}What is a closure in Go, and how did Go 1.22 change what closures capture inside a
forloop?func counter() func() int { n := 0 // captured by the closure, outlives counter() return func() int { n++ return n }…When does
init()run relative to imports and package-level variables, and why is putting real work in it discouraged?// lookup/lookup.gopackage lookup var a = b + 1 // dependency order, not source order: b is set first, so a is 3var b = 2…What is the difference between a type definition
type UserID stringand a type aliastype UserID = string?type UserID string // a new typetype Name = string // an alias: Name and string are the same type func (id UserID) Valid() bool { return strings.HasPrefix(string(id), "u_") } type Set[T comparable] = map[T]struct{} // Go 1.24: generic alias…What has changed in Go over the last few releases, and which of those changes affect everyday code?