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
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
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".
| Type | Zero value |
|---|---|
| Numbers | 0, 0.0 |
bool | false |
string | "" |
| Pointer, slice, map, channel, function, interface | nil |
| Array, struct | Every element or field set to its own zero value |
:=needs at least one new name on the left.x := 1twice in the same scope is a compile error.- Use
var x Twhen the zero value is what you want; use:=when you have a value.
Constants and iota
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
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.
| Type | Size | Use |
|---|---|---|
int, uint | 64 bits on 64-bit machines | The default for counts, indexes and money in the smallest unit (paise) |
int8 to int64, uint8 to uint64 | As named | Binary formats, protocols, memory-sensitive structs |
float64, float32 | 64, 32 bits | float64 is the default. Never for money. |
bool | 1 byte | true, false; no truthiness: if n does not compile for an int |
string | Header of 16 bytes | Immutable bytes, usually UTF-8 |
byte | Alias for uint8 | One byte of raw data |
rune | Alias for int32 | One 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
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.
float64tointtruncates; it does not round. Usemath.Roundfirst if you need rounding.string(65)is"A", not"65".go vetwarns aboutstring(int); usestrconv.Itoafor digits.
The := shadowing gotcha
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
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.
| Operation | Gives | Python 3 equivalent |
|---|---|---|
len(s) | Bytes | len(s.encode()) |
utf8.RuneCountInString(s) | Characters (code points) | len(s) |
s[i] | A byte | s.encode()[i] |
for i, r := range s | Byte offset and rune | enumerate(s), but offsets skip |
[]byte(s), []rune(s) | A mutable copy | bytearray(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
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.
| Python | Go |
|---|---|
s.strip(), s.split(","), ",".join(xs) | strings.TrimSpace, strings.Split, strings.Join |
"x" in s, s.startswith, s.find | strings.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 loop | strings.Builder |
fmt verbs
Printf and Sprintf use C-style verbs. %v prints anything; the rest control the format. go vet checks that each verb matches its argument.
| Verb | Prints |
|---|---|
%v | Default format of any value |
%+v | Struct with field names. The one to use in logs. |
%#v | Go syntax, like Python's repr |
%T | The type, like type(x) |
%d, %5d, %-5d, %05d | Integer, padded right, padded left, zero-padded |
%s, %q | String, quoted string |
%x, %X | Hex (of a number or of a string's bytes) |
%.2f, %8.2f, %e | Float with 2 decimals, width 8, scientific |
%t, %c, %U, %% | Bool, character, Unicode code point, a literal % |
%w | Only 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
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
Go has no while or do. One keyword covers four shapes.
| Shape | Python 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
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
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
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.
fallthroughruns the next case body without testing its condition. It is rare in real code.breakinside aswitchleaves 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
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
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
deferruns, 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
recoverworks (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
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
returnreturns 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
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
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 isnil; 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
nonlocalkeyword.
The (value, error) convention
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
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.
inittakes no arguments, returns nothing and cannot be called by name.- Keep
initsmall. 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
- The slice header
- make, append and growth
- Slicing shares the backing array
- Full slice expression
- copy and deleting an element
- nil slice versus empty slice
- The slices package
- Maps
- Writing to a nil map panics
- Map iteration order and the maps package
- Map of slices and the set idiom
- 2-D slices
Arrays are values
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
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.
len(s): elements you can index.cap(s): elements from the pointer to the end of the backing array.s[i]pastlenpanics, buts[:cap(s)]reslices up to capacity.- Python's
xs[1:4]copies; Go's shares.
make, append and growth
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)plusappendavoids every reallocation.make([]T, n)already hasnzero elements; appending to it adds after them. A common bug.
Slicing shares the backing array
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.
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
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
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
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
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.
| Python | Go |
|---|---|
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_left | slices.BinarySearch (on sorted input) |
xs.reverse(), max(xs) | slices.Reverse, slices.Max (panics on empty) |
xs[:], xs == ys | slices.Clone, slices.Equal |
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.
deleteon a missing key is a no-op.m[k]++works on a missing key because it starts from the zero value: nodefaultdictneeded.- Map elements are not addressable:
&m[k]andm[k].Field = xdo not compile.
Writing to a nil map panics
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
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.Keysandmaps.Valuesreturn iterators; wrap them inslices.Sortedorslices.Collect.maps.Cloneis a shallow copy;maps.Equalcompares contents;maps.DeleteFuncfilters 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
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
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 *
&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
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
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.
| Passed | What is copied | Callee writes an element | Callee appends or reassigns |
|---|---|---|---|
| Array, struct | All the data | Not visible | Not visible |
| Slice | Pointer, len, cap | Visible | Not visible: return the new slice |
| Map | A pointer to the hash table | Visible (also inserts and deletes) | Reassigning the variable: not visible |
| Pointer | The address | Visible | Pointing 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{}
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
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
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
ainonHeap: its address is returned, so it moves to the heap. TheainonStackis not mentioned: it stays on the stack. - The last two lines are the
intvalues passed tofmt.Println, which takesanyarguments; 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
| Python | Go | Note |
|---|---|---|
x = 1 | x := 1 or var x int = 1 | Type fixed at compile time |
None | nil (pointers, slices, maps...) or the zero value | An int cannot be nil |
int (unbounded) | int (64-bit, wraps) | math/big for huge numbers |
str of code points | string of UTF-8 bytes | len counts bytes |
list | []T slice | Slicing shares memory |
dict | map[K]V | Random iteration order |
set | map[T]struct{} | No built-in set |
tuple return | Multiple results | Not a value you can store |
while | for cond { } | One loop keyword |
if/elif chain, match | switch | No fallthrough by default |
try/finally, with | defer | Runs at function exit |
raise / except | return err / if err != nil | Next page |
*args | nums ...int, call with xs... | No **kwargs, no defaults |
lambda | func(x int) int { ... } | Any number of statements |
nonlocal | Not needed | Closures capture variables directly |
f"{x:.2f}" | fmt.Sprintf("%.2f", x) | %v for anything |
int("42"), str(42) | strconv.Atoi, strconv.Itoa | Atoi returns an error |
sorted(d) | slices.Sorted(maps.Keys(d)) | Go 1.23+ |
Cheat sheet
| Topic | Remember |
|---|---|
| Declare | var x T anywhere, x := v in functions; unused locals and imports do not compile |
| Zero values | 0, "", false, nil; structs and arrays zeroed field by field |
| Enums | type Kind int + const ( A Kind = iota; B; C ) |
| Conversions | Always explicit: float64(n); text via strconv |
| Shadowing | := in an inner block makes a new variable |
| Strings | Immutable UTF-8 bytes; range gives runes; build with strings.Builder |
| Loops | for only; range n; per-iteration variables since 1.22; labels for nested break |
| switch | No fallthrough by default; several values per case; tagless for conditions |
| defer | LIFO at function exit; arguments evaluated at the defer line |
| Functions | Multiple results, (value, error) last, variadic ...T, closures share captured variables |
| Init order | Imported packages, package variables by dependency, init()s, then main |
| Slices | Header (ptr, len, cap); s = append(s, x); sub-slices alias; a[l:h:h] or slices.Clone to cut the link |
| Maps | Comma-ok for presence; nil map write panics; random order, sort keys; set is map[T]struct{} |
| Pointers | Pass by value always; pointer to change the caller's value; no arithmetic; nil dereference panics |
| Stack or heap | The compiler decides; see it with go build -gcflags=-m |
Next: Structs, Interfaces and Errors, where these values get methods, behaviour and proper error handling.