Learnings

Go, part 2 of 5

Go Basics: Types, Control Flow and Functions

The core language for a Python developer: variables and zero values, constants and iota, strings as UTF-8 bytes, the one loop, switch and defer, functions and closures, slices and maps with their aliasing traps, and pointers. Every program on this page was run on Go 1.27 and shows its real output.

Values, types and strings

Part 1 of 5 · declarations, constants, conversions and text

Go is statically typed with type inference. Every variable has a type fixed at compile time and a usable zero value from the moment it is declared.

Program shape in three lines

Values, types and strings

Recap from part 1: a file starts with package main, then its import list, then declarations; the program starts in func main(). Every example below is one complete file you can save as main.go and run with go run ..

Two compile errors a Python developer meets on day one: an unused import and an unused local variable both stop the build. Use the value or assign it to _.

var, := and zero values

Values, types and strings

var works everywhere and can omit the value; := declares and assigns in one step but only inside functions. A variable declared without a value holds its type's zero value, never garbage and never "undefined".

TypeZero value
Numbers0, 0.0
boolfalse
string""
Pointer, slice, map, channel, function, interfacenil
Array, structEvery element or field set to its own zero value
  • := needs at least one new name on the left. x := 1 twice in the same scope is a compile error.
  • Use var x T when the zero value is what you want; use := when you have a value.

Constants and iota

Values, types and strings

Constants are fixed at compile time. Inside a const ( ... ) block, iota counts from 0 on each line, and a line with no expression repeats the previous one. This is Go's enum.

An untyped constant (const limit = 10) has arbitrary precision and takes the type its use needs, so it fits an int64 or a float64. A typed constant behaves like a variable of that type:

Interview line: Go has no enum keyword. The idiom is a named type (type Kind int) plus an iota block, so a Kind cannot be mixed up with a plain int by accident.

Basic types

Values, types and strings

Unlike Python, integers have a fixed size and silently wrap on overflow. int is 64 bits on every 64-bit platform you will deploy to.

TypeSizeUse
int, uint64 bits on 64-bit machinesThe default for counts, indexes and money in the smallest unit (paise)
int8 to int64, uint8 to uint64As namedBinary formats, protocols, memory-sensitive structs
float64, float3264, 32 bitsfloat64 is the default. Never for money.
bool1 bytetrue, false; no truthiness: if n does not compile for an int
stringHeader of 16 bytesImmutable bytes, usually UTF-8
byteAlias for uint8One byte of raw data
runeAlias for int32One Unicode code point

Gotcha: integer division truncates toward zero, so -7/2 is -3 and -7%3 is -1. Python floors: -7//2 is -4 and -7%3 is 2.

Explicit conversions and strconv

Values, types and strings

Go never converts between numeric types for you, not even int to int64. Write T(x). Text to number and back goes through strconv, which returns an error instead of raising.

  • float64 to int truncates; it does not round. Use math.Round first if you need rounding.
  • string(65) is "A", not "65". go vet warns about string(int); use strconv.Itoa for digits.

The := shadowing gotcha

Values, types and strings

Every { } block is a new scope. A := inside it creates a new variable even if one with the same name exists outside, and the outer one is silently left alone.

Interview line: the classic bug is x, err := f() inside an if or loop when you meant to set an outer x. Declare the variables before the block and use =. Python has no block scope, so this trap is new.

Strings are UTF-8 bytes

Values, types and strings

A Go string is an immutable sequence of bytes. len counts bytes, indexing returns a byte, and range decodes UTF-8 into runes. The rupee sign takes 3 bytes.

OperationGivesPython 3 equivalent
len(s)Byteslen(s.encode())
utf8.RuneCountInString(s)Characters (code points)len(s)
s[i]A bytes.encode()[i]
for i, r := range sByte offset and runeenumerate(s), but offsets skip
[]byte(s), []rune(s)A mutable copybytearray(s.encode()), list(s)

Gotcha: s[0] = 'x' does not compile: cannot assign to s[0] (neither addressable nor a map index expression). Slicing s[1:3] slices bytes and can cut a character in half.

strings.Builder and the strings package

Values, types and strings

Because strings are immutable, s += x in a loop copies every time. Build long strings with strings.Builder. Everyday helpers are functions in strings, not methods on the string.

PythonGo
s.strip(), s.split(","), ",".join(xs)strings.TrimSpace, strings.Split, strings.Join
"x" in s, s.startswith, s.findstrings.Contains, strings.HasPrefix, strings.Index (-1 if absent)
s.split() (on whitespace)strings.Fields
s.partition("=")strings.Cut
s.lower() == t.lower()strings.EqualFold
"".join(parts) in a loopstrings.Builder

fmt verbs

Values, types and strings

Printf and Sprintf use C-style verbs. %v prints anything; the rest control the format. go vet checks that each verb matches its argument.

VerbPrints
%vDefault format of any value
%+vStruct with field names. The one to use in logs.
%#vGo syntax, like Python's repr
%TThe type, like type(x)
%d, %5d, %-5d, %05dInteger, padded right, padded left, zero-padded
%s, %qString, quoted string
%x, %XHex (of a number or of a string's bytes)
%.2f, %8.2f, %eFloat with 2 decimals, width 8, scientific
%t, %c, %U, %%Bool, character, Unicode code point, a literal %
%wOnly in fmt.Errorf: wraps an error so errors.Is can find it (next page)

Control flow

Part 2 of 5 · if, for, switch, labels and defer

No parentheses around conditions, braces always required, and one loop keyword. defer replaces most uses of try/finally.

if with a short statement

Control flow

An if may run one statement before its condition. Variables declared there live only in the if and its else branches, which keeps err from leaking into the rest of the function.

No truthiness: the condition must be a bool. Write if len(xs) > 0, if s != "", if p != nil. There is no ternary operator either.

for: the only loop

Control flow

Go has no while or do. One keyword covers four shapes.

ShapePython equivalent
for i := 0; i < n; i++ { }for i in range(n): with full control of the step
for cond { }while cond:
for { }while True:
for i := range n { }for i in range(n): (Go 1.22+)
for i, v := range xs { }for i, v in enumerate(xs):

i++ is a statement, not an expression: x = i++ does not compile, and there is no ++i.

range over slices, maps, strings and channels

Control flow

range yields two values: index and element for slices, key and value for maps, byte offset and rune for strings, and just the value for a channel. Drop one with _, or write only the first.

  • The element variable is a copy. To modify elements, index the slice: xs[i] = ....
  • Map order is random on purpose: sort the keys when order matters (see map iteration order).
  • Ranging over a channel stops when it is closed. Channels are covered on part 4.

Per-iteration loop variables

Control flow

Since Go 1.22 each iteration gets its own copy of the loop variable, so closures and goroutines started in a loop see the value from their own iteration.

Interview line: before Go 1.22 the loop variable was shared, and this program printed 3 3 3 (checked by setting go 1.21 in go.mod with a three-clause loop). Old code fixes it with i := i inside the loop. The behaviour follows the go line of the module, not the compiler version.

switch

Control flow

Cases do not fall through: each case breaks by itself. A case may list several values, and a switch with no expression is a clean if / else if chain.

  • Cases are evaluated top to bottom; the first match wins.
  • fallthrough runs the next case body without testing its condition. It is rare in real code.
  • break inside a switch leaves the switch, not the enclosing loop. Use a label to leave the loop.
  • A type switch (switch v := x.(type)) comes with interfaces on the next page.

break and continue with labels

Control flow

A label names a loop so that break or continue can target it from an inner loop or a switch. Python needs a flag variable or a function for this.

defer

Control flow

defer schedules a call to run when the surrounding function returns, whether normally or by panic. It is how Go closes files, unlocks mutexes and ends spans, written right next to the open.

  • Deferred calls run last in, first out.
  • Arguments are evaluated when defer runs, not when the call runs: the log line shows 100, not 999.
  • Deferring inside a long loop holds every resource until the function ends. Move the loop body into its own function.
  • A deferred closure can read and change named results; that is how recover works (next page).

Functions

Part 3 of 5 · results, variadics, closures and init

Functions are first-class values. There are no default arguments, no keyword arguments and no overloading; Go uses several functions, variadics or an options struct instead.

Multiple and named results

Functions

A function can return several values. This is not a tuple: you must receive all of them, using _ for the ones you skip. Parameters of the same type can share it: a, b int.

  • Named results start at their zero values and a bare return returns them.
  • Use names when they document two results of the same type, like (notes, coins int), or when a deferred function must change a result.
  • Avoid naked returns in functions longer than a few lines: the reader cannot see what is returned.

Variadic functions

Functions

A final parameter ...T accepts zero or more values and arrives as a []T. Pass an existing slice with xs....

Gotcha: f(xs...) passes the slice itself, not a copy. If the function writes to nums[0], the caller's slice changes.

Function values, closures and anonymous functions

Functions

A function can be stored in a variable, passed as an argument and returned. A function literal that uses variables from its surroundings is a closure: it keeps those variables alive and shares them, not copies of them.

  • A function type is written func(string) string. Its zero value is nil; calling a nil function panics.
  • Unlike Python's lambda, a function literal can hold any number of statements.
  • Unlike Python, a closure can assign to captured variables without a nonlocal keyword.

The (value, error) convention

Functions

Functions that can fail return the error as their last result. The caller checks it at once; nil means success. Errors, wrapping and custom error types are covered on the next page.

When the error is not nil, treat the other results as meaningless unless the function documents otherwise.

init and initialisation order

Functions

Package-level variables are initialised first, in dependency order rather than source order. Then every init() function runs, in the order they appear, and finally main.

  • Across packages: every imported package is fully initialised before the package that imports it.
  • init takes no arguments, returns nothing and cannot be called by name.
  • Keep init small. Hidden work at import time (opening connections, reading config) makes tests and startup hard to reason about.

Arrays, slices and maps

Part 4 of 5 · the collections and their traps

A slice is Go's list and a map is its dict. Both are small headers that point at shared storage, and most collection bugs in interviews come from that sharing.

Arrays are values

Arrays, slices and maps

An array has a fixed length that is part of its type: [3]int and [4]int are different types. Assigning or passing an array copies every element.

You rarely declare arrays directly. They are the storage under slices, and useful as fixed-size map keys ([2]int for a grid cell) because arrays are comparable and slices are not.

The slice header

Arrays, slices and maps

A slice is a three-word struct: a pointer to an element of a backing array, a length and a capacity. Copying a slice copies those three words, not the elements.

The slice sees 10, 20, 30 (len 3) and may grow into 40 and 50 without reallocating (cap 5).
  • len(s): elements you can index. cap(s): elements from the pointer to the end of the backing array.
  • s[i] past len panics, but s[:cap(s)] reslices up to capacity.
  • Python's xs[1:4] copies; Go's shares.

make, append and growth

Arrays, slices and maps

append writes into spare capacity if there is any; otherwise it allocates a bigger array, copies, and returns a slice pointing to the new one. That is why you must always write s = append(s, x).

  • Growth doubles while the slice is small, then slows to about 1.25x for large slices. The exact numbers are a runtime detail and round up to allocator size classes.
  • make([]T, len, cap) preallocates. When you know the final size, make([]T, 0, n) plus append avoids every reallocation.
  • make([]T, n) already has n zero elements; appending to it adds after them. A common bug.

Slicing shares the backing array

Arrays, slices and maps

This is the most asked slice question. A sub-slice writes into its parent, and append on a sub-slice with spare capacity overwrites the parent's next element. Once append reallocates, the link is silently broken.

Before the second append both slices point at one array; after it, first owns a new copy.

Interview line: "Whether the caller sees an append depends on capacity." Never rely on it. If a function gets a sub-slice it may append to, give it a full slice expression or a clone.

Full slice expression

Arrays, slices and maps

a[low:high:max] also sets the capacity to max - low. With capacity equal to length, the next append must reallocate, so the parent is safe.

copy and deleting an element

Arrays, slices and maps

copy(dst, src) copies min(len(dst), len(src)) elements and returns that number. It never grows dst, so a zero-length destination receives nothing.

The append(s[:i], s[i+1:]...) idiom shifts elements in place and reuses the same array. slices.Delete(s, i, i+1) does the same and is clearer.

nil slice versus empty slice

Arrays, slices and maps

A nil slice has no backing array; an empty slice has one of length zero. Both have len 0, both can be ranged over and appended to. The difference shows in == nil checks and in JSON.

Rule: declare with var s []T and test with len(s) == 0, not s == nil. Return []T{} only when an API must send [] rather than null.

The slices package

Arrays, slices and maps

Since Go 1.21 the generic slices package covers what Python does with built-ins and list methods. Functions that rearrange (Sort, Reverse) work in place; functions that may grow (Insert, Delete) return the new slice.

PythonGo
xs.sort(), sorted(xs)slices.Sort(xs), slices.Sorted(seq)
xs.sort(key=len)slices.SortFunc(xs, cmp), slices.SortStableFunc
x in xs, xs.index(x)slices.Contains, slices.Index (-1 if absent)
bisect.bisect_leftslices.BinarySearch (on sorted input)
xs.reverse(), max(xs)slices.Reverse, slices.Max (panics on empty)
xs[:], xs == ysslices.Clone, slices.Equal

Maps

Arrays, slices and maps

A map is a hash table from comparable keys to values. Reading a missing key returns the zero value, never an error, so use the comma-ok form to tell "absent" from "zero".

  • Keys must be comparable: numbers, strings, bools, pointers, arrays and structs of those. Slices, maps and functions cannot be keys.
  • delete on a missing key is a no-op.
  • m[k]++ works on a missing key because it starts from the zero value: no defaultdict needed.
  • Map elements are not addressable: &m[k] and m[k].Field = x do not compile.

Writing to a nil map panics

Arrays, slices and maps

A map declared with var m map[K]V is nil. Reading, len, range and delete all work on it; writing panics. Create maps with make or a literal.

Where it bites: a struct with a map field. The struct's zero value has a nil map, so the first write panics until a constructor does make.

Map iteration order and the maps package

Arrays, slices and maps

Go randomises map iteration order on purpose so nobody depends on it. Python dicts keep insertion order; Go maps do not. Sort the keys when output must be stable. The first line below changes between runs.

  • maps.Keys and maps.Values return iterators; wrap them in slices.Sorted or slices.Collect.
  • maps.Clone is a shallow copy; maps.Equal compares contents; maps.DeleteFunc filters in place.
  • fmt.Println(m) sorts keys when printing, which can hide the random order in quick tests.

Map of slices and the set idiom

Arrays, slices and maps

Because a missing key gives a nil slice and append accepts nil, grouping needs no setup. Go has no set type; a map[T]struct{} is the idiom, since the empty struct takes no memory.

map[T]bool also works and reads more easily (if seen[x]); struct{} stores nothing per entry and makes the intent explicit.

2-D slices

Arrays, slices and maps

A 2-D slice is a slice of slices: allocate the outer slice, then each row. Rows may have different lengths.

Python trap, Go version: [[0]*3]*2 shares one row in Python. In Go, forgetting the inner make leaves nil rows, and grid[1][2] = 7 panics with index out of range.

Pointers and recap

Part 5 of 5 · addresses, pass by value, the heap, and a summary

Python hides pointers: every name is a reference. Go makes them explicit, and everything, including pointers, is passed by value.

& and *

Pointers and recap

&x takes the address of x; its type is *T. *p reads or writes the value it points to. Copying a pointer gives a second pointer to the same value.

There is no pointer arithmetic: p++ on a *int fails with invalid operation: p++ (non-numeric type *int). Pointers are only references, so the garbage collector can track them.

Pass by value, always

Pointers and recap

A function receives a copy of every argument. Passing a struct copies the whole struct, so changes stay inside the function. Pass a pointer when the function must change the caller's value or the struct is large.

a.Balance works on both Account and *Account: Go dereferences for you. Structs and methods with pointer receivers are the subject of the next page.

Why slices and maps feel like references

Pointers and recap

They are still passed by value, but the value is a small header that points at shared storage. Writing an element goes through the pointer and is visible; changing the header itself (as append does) is not.

PassedWhat is copiedCallee writes an elementCallee appends or reassigns
Array, structAll the dataNot visibleNot visible
SlicePointer, len, capVisibleNot visible: return the new slice
MapA pointer to the hash tableVisible (also inserts and deletes)Reassigning the variable: not visible
PointerThe addressVisiblePointing it elsewhere: not visible

Interview line: "Go is always pass by value. Slices, maps, channels and pointers are values that contain pointers." That is why the standard idiom is s = append(s, x).

new versus &T{}

Pointers and recap

new(T) allocates a zero T and returns *T. &T{...} does the same but lets you set fields, so it is what you will write for structs. new is mostly seen with basic types.

Returning the address of a local variable is safe in Go (unlike C): the compiler moves it to the heap when needed, as the escape analysis chapter shows.

Nil pointer dereference

Pointers and recap

A pointer's zero value is nil. Reading a field through a nil pointer panics at run time, Go's version of Python's AttributeError: 'NoneType' object has no attribute.

Check if a == nil wherever a pointer may be absent, and prefer returning a value plus an error over returning a possibly nil pointer.

Escape analysis: stack or heap

Pointers and recap

You never choose where a variable lives. The compiler keeps it on the cheap stack when it can prove the variable does not outlive the function, and moves it to the garbage-collected heap when it might.

  • Line 13 is the a in onHeap: its address is returned, so it moves to the heap. The a in onStack is not mentioned: it stays on the stack.
  • The last two lines are the int values passed to fmt.Println, which takes any arguments; boxing into an interface often causes small allocations.
  • Fewer heap allocations mean less GC work. Measure with benchmarks before rewriting code for this.

Python to Go quick comparison

Pointers and recap

PythonGoNote
x = 1x := 1 or var x int = 1Type fixed at compile time
Nonenil (pointers, slices, maps...) or the zero valueAn int cannot be nil
int (unbounded)int (64-bit, wraps)math/big for huge numbers
str of code pointsstring of UTF-8 byteslen counts bytes
list[]T sliceSlicing shares memory
dictmap[K]VRandom iteration order
setmap[T]struct{}No built-in set
tuple returnMultiple resultsNot a value you can store
whilefor cond { }One loop keyword
if/elif chain, matchswitchNo fallthrough by default
try/finally, withdeferRuns at function exit
raise / exceptreturn err / if err != nilNext page
*argsnums ...int, call with xs...No **kwargs, no defaults
lambdafunc(x int) int { ... }Any number of statements
nonlocalNot neededClosures capture variables directly
f"{x:.2f}"fmt.Sprintf("%.2f", x)%v for anything
int("42"), str(42)strconv.Atoi, strconv.ItoaAtoi returns an error
sorted(d)slices.Sorted(maps.Keys(d))Go 1.23+

Cheat sheet

Pointers and recap

TopicRemember
Declarevar x T anywhere, x := v in functions; unused locals and imports do not compile
Zero values0, "", false, nil; structs and arrays zeroed field by field
Enumstype Kind int + const ( A Kind = iota; B; C )
ConversionsAlways explicit: float64(n); text via strconv
Shadowing:= in an inner block makes a new variable
StringsImmutable UTF-8 bytes; range gives runes; build with strings.Builder
Loopsfor only; range n; per-iteration variables since 1.22; labels for nested break
switchNo fallthrough by default; several values per case; tagless for conditions
deferLIFO at function exit; arguments evaluated at the defer line
FunctionsMultiple results, (value, error) last, variadic ...T, closures share captured variables
Init orderImported packages, package variables by dependency, init()s, then main
SlicesHeader (ptr, len, cap); s = append(s, x); sub-slices alias; a[l:h:h] or slices.Clone to cut the link
MapsComma-ok for presence; nil map write panics; random order, sort keys; set is map[T]struct{}
PointersPass by value always; pointer to change the caller's value; no arithmetic; nil dereference panics
Stack or heapThe compiler decides; see it with go build -gcflags=-m

Next: Structs, Interfaces and Errors, where these values get methods, behaviour and proper error handling.