My account

Go language basics

Go is a small language, but a few of its behaviors come up again and again in interviews. If you understand zero values, the slice header and the shared array, how maps behave, value and pointer receivers, small interfaces and the nil trap, embedding, generics and the order of defer, you can answer most basic questions.

Not reviewedWritten with AI helpReading time: 20 minOnline shop exampleGo 1.25 code

Author: bezzad

Contents

The problem: a cart that changes by itself

The order service of our shop is written in Go. This week we have three bug reports:

  1. On the checkout page two orders are made from one cart. The first order has an item that the user added only to the second order.
  2. The stock service crashes on the first request after a deploy with “assignment to entry in nil map”.
  3. The MarkPaid method is called, but the order is still “not paid”.

All three bugs come from a few simple behaviors of the language that you must know well. In this lesson we look at them one by one.

Zero values

In Go every variable has a zero value. A variable without a value is not empty or broken:

type Item struct {
	SKU   string
	Price int // in cents
	Qty   int
}

type Cart struct {
	Items    []Item
	Coupon   string
	Discount int
}

var c Cart
// c.Items is nil, c.Coupon is "", c.Discount is 0
c.Items = append(c.Items, Item{SKU: "pen", Price: 200, Qty: 1})
  1. A number is zero, a string is empty and a bool is false.
  2. Pointers, slices, maps, channels, functions and interfaces have nil as their zero value.
  3. A nil slice is ready to use. You can take its length, loop over it and append to it.

A good design rule in Go: build your types so that their zero value is useful. For example, sync.Mutex and bytes.Buffer work without any setup.

The slice header and the shared array

A slice is a small header with three parts: a pointer to an array, a length (len) and a capacity (cap). The data lives in the array, not in the slice.

base := make([]string, 0, 4)
base = append(base, "pen", "cup")
a := append(base, "mug")
b := append(base, "bag")
fmt.Println(a[2], b[2]) // bag bag
  1. The base cart has length 2 and capacity 4. So there are two free slots in the array.
  2. The first append sees free space. It writes “mug” into slot 2 of the same array and returns a header with length 3.
  3. The second append also starts from base, with length 2. It sees the same slot 2 and writes “bag” over it.
  4. All three slices point to one array. So a now has “bag” too. This is our first bug.
Slice header: pointer, length, capacitybaselen=2 cap=4a := append(base, mug)len=3 cap=4b := append(base, bag)len=3 cap=4pencupmugbagfreeShared backing array with capacity 4Both appends write into slot 2. Now a has bag too.
Three slice headers point to one shared array. Because there is free capacity, both appends write into the same slot.

The append function makes a new array only when the capacity is not enough. So its behavior depends on the capacity, and the capacity depends on how the slice was built. That is why this bug does not show up in a test with a slice literal, but shows up in production.

The fix: when you want two independent results, copy first:

a := append(slices.Clone(base), "mug")
b := append(slices.Clone(base), "bag")

Two more points about slices:

  1. If you know the size, give the capacity from the start. This avoids building and copying the array several times:
func skus(items []Item) []string {
	out := make([]string, 0, len(items))
	for _, it := range items {
		out = append(out, it.SKU)
	}
	return out
}
  1. A small slice of a big array keeps the whole array in memory. If you need only a small part for a long time, copy it with slices.Clone.

Maps

A map is a hash table. Interviewers often ask about three of its behaviors:

stock := map[string]int{"pen": 10, "cup": 0}

n, ok := stock["mug"] // n is 0, ok is false
for _, sku := range slices.Sorted(maps.Keys(stock)) {
	fmt.Println(sku, stock[sku])
}

var empty map[string]int
_ = empty["x"]  // reading a nil map is fine
empty["x"] = 1 // panic: assignment to entry in nil map
  1. Reading a missing key returns the zero value. To tell “it is zero” from “it is missing”, use the two-result form with ok.
  2. The loop order over a map is random on purpose. If you need a fixed order, sort the keys.
  3. Writing to a nil map panics. This is our second bug: a map field in a struct that was never made with make. Reading from a nil map is fine.
  4. A map is not safe for concurrent use. If several goroutines write at the same time, the runtime stops the program with a fatal error. Use a mutex.

Methods: value or pointer receiver

Every method has a receiver. The receiver can be a value or a pointer:

type Order struct {
	ID     int64
	Status string
	Items  []Item
}

// Value receiver: works on a copy
func (o Order) IsPaid() bool { return o.Status == "paid" }

// Pointer receiver: changes the real order
func (o *Order) MarkPaid() { o.Status = "paid" }
  1. A value receiver gets a copy of the struct. Every change is on the copy and is lost when the method returns. This is our third bug: MarkPaid was written with a value receiver.
  2. A pointer receiver reaches the struct itself and can change it. It also makes no copy, which matters for a big struct.
  3. If one method has a pointer receiver, make the other methods of that type pointer receivers too, to stay consistent.
  4. A type with a mutex must never be copied, so all its methods have pointer receivers. The go vet tool reports a copied lock.

This choice also changes the method set. The method set of Order has only the value receiver methods. The method set of a pointer to Order has both kinds. So only the pointer fits into an interface that needs MarkPaid:

type Payable interface{ MarkPaid() }

var p Payable = &order // OK
var q Payable = order  // compile error
*OrderOrderIsPaid()MarkPaid()type Payable interfaceMarkPaid()var p Payable = &ordervar p Payable = orderAn Order value does not have MarkPaid. The pointer has both methods.
An Order value has only the value receiver methods. A pointer to Order has both kinds of methods and fits the interface.

Interfaces: small and implicit

In Go a type does not say which interfaces it implements. If it has the needed methods, it implements the interface automatically:

type Notifier interface {
	Notify(orderID int64, msg string) error
}

type EmailNotifier struct{ from string }

func (e *EmailNotifier) Notify(orderID int64, msg string) error {
	// send the email ...
	return nil
}

type Checkout struct {
	notify Notifier
}

func NewCheckout(n Notifier) *Checkout {
	return &Checkout{notify: n}
}
  1. Keep interfaces small. One or two methods is best, like io.Reader and io.Writer. The bigger it is, the harder it is to implement and test.
  2. Define the interface where it is used, not next to the implementation. Here the checkout package says what it needs.
  3. A common rule: “accept interfaces, return structs”. NewCheckout takes a Notifier, so a test can pass a fake. But it returns a pointer to a struct.
  4. Do not make an interface for every struct up front. Make it when you have two real implementations, or when a test needs it.

The nil trap in interfaces

An interface value has two parts: a type and a value. It equals nil only when both parts are empty. If you put a nil pointer into an interface, the type part is filled:

func charge(amount int) error {
	var perr *PaymentError
	if amount <= 0 {
		perr = &PaymentError{Code: "bad_amount"}
	}
	return perr // never a nil error
}
Empty interface valueA nil pointer inside an interfacereturn nilreturn perr // perr == niltypevaluenilniltypevalue*PaymentErrornilerr == nil → trueerr == nil → falseAn interface value is nil only when both type and value are empty.
An interface value is a pair of type and value. A nil pointer of type PaymentError makes a non-nil interface.

The fix: return the literal nil on the success path. The lesson “Errors in Go” explains this trap in more detail.

Embedding

Go has no inheritance. Instead, you can embed one type inside another:

type Base struct {
	ID        int64
	CreatedAt time.Time
}

func (b Base) Key() string { return strconv.FormatInt(b.ID, 10) }

type Customer struct {
	Base // embedded: fields and methods are promoted
	Email string
}

c := Customer{Base: Base{ID: 7}, Email: "sara@example.com"}
fmt.Println(c.ID, c.Key()) // 7 7
  1. The fields and methods of Base are “promoted” to Customer. You can write c.ID instead of c.Base.ID.
  2. This is not inheritance. The receiver of Key is still Base, not Customer. There are no virtual methods.
  3. Be careful: embedding a type also exports all its public methods. For example, embedding sync.Mutex in a public struct shows Lock and Unlock to everybody. A named field is usually better.

Generics

Since Go 1.18, functions and types can have type parameters:

type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](xs []T) T {
	var total T
	for _, x := range xs {
		total += x
	}
	return total
}

prices := []int{200, 1500, 990}
fmt.Println(Sum(prices)) // 2690
  1. A constraint is an interface that says which types T can be. The ~ sign means “any type whose underlying type is this”, for example a Cents type built on int.
  2. The compiler infers the type. You do not need to write Sum with int.
  3. The standard packages slices, maps and cmp do most common jobs with generics, like sorting, searching and finding the maximum.

When not to use generics? When you have only one type, or when a simple interface is enough. Generics are for shared code over several types, like a data structure or a helper function, not for business logic.

The order of defer

The defer statement keeps a call for the moment the function returns. It has two rules:

for i := range 3 {
	defer fmt.Println("defer", i)
}
fmt.Println("body")
// body, defer 2, defer 1, defer 0
  1. The order is reversed (the last defer runs first), like a stack.
  2. The arguments are evaluated at the defer statement, not when the call runs. That is why each line prints the i of its own loop turn.
  3. A defer belongs to the function, not to the block. A defer inside a long loop does not run until the function ends, so resources stay open.
Loop variables since Go 1.22 Since Go 1.22 each turn of a for loop has its own variable. So closures and goroutines that capture the loop variable no longer all see the last value. You may still see this bug in older code.

Common mistakes

Mistake Result The right way
Two appends on one base slice with free capacity The two results overwrite the same array slot. Copy first with slices.Clone.
Writing to a map that was never made with make A panic at run time Make the map in the constructor.
Relying on the loop order of a map The output changes every time. Sort the keys.
A method that changes data, with a value receiver The change is on a copy and is lost. A pointer receiver
Returning a nil pointer as an error The error is never nil. Return the literal nil.
A big interface next to the implementation Hard to implement and test. A small interface on the user’s side
Generics for logic with one type The code is harder to read. Simple code with a concrete type
A defer inside a long loop Resources stay open until the function ends. Move the loop body into its own function.

Summary in seven lines

  1. Every type has a zero value. Build types so that their zero value is useful.
  2. A slice is a header over an array. The append function writes into the same array while there is capacity.
  3. Use slices.Clone for an independent result, and give the capacity up front when you know the size.
  4. Writing to a nil map panics, map order is random, and maps are not safe for concurrent use.
  5. A method that changes data needs a pointer receiver. The receiver affects method sets and interfaces.
  6. Interfaces are small and live on the user’s side. A nil pointer inside an interface is not nil.
  7. Embedding is not inheritance, generics are for shared code over several types, and defer runs in reverse at the end of the function.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.