Pointers in Practice
A guide to using pointers in Go effectively - passing pointers to functions, trade-offs between pointers and values, and pointer comparison.
Pointers give you direct access to the memory that holds your data. Once you can declare them and dereference them, the next step is deciding where and how to use them in real code. This group covers three decisions you will face repeatedly: handing a pointer to a function instead of a value, choosing whether a variable should be a pointer or a value in the first place, and understanding what it means when you compare two pointers.
Passing Pointers to Functions
Go always passes arguments by value. Passing a pointer copies the address, an 8-byte value on a 64-bit machine, instead of the whole value, and the function can then read and overwrite the caller's original variable through that address. A pointer parameter can be nil, so a function must decide whether nil is a valid input and guard against it. Slices, maps, and channels already share their underlying data when passed by value, so they usually need no pointer at all.
Pointers vs Values Trade-offs
Values give you isolation and safety: a function that receives a value works on its own copy. Pointers give you shared access and the ability to mutate, plus a way to express that a value may be absent, at the cost of possible nil panics and heap allocation when the value escapes. Default to values, and introduce a pointer only when the code needs mutation, optionality, or to avoid copying something genuinely large.
Pointer Comparison
Go allows == and != on pointers of the same type. The comparison answers one question: do these two pointers hold the same memory address? It does not compare the values at those addresses. A pointer can also be compared to nil. Ordering operators (<, <=, >, >=) are not defined on pointers at all. Comparing pointers of different types is a compile-time error, while dereferencing a nil pointer is never a compile-time error, it compiles and panics at runtime, so guard with a nil check first.
Passing Pointers to Functions
Learn how to pass pointers as function arguments in Go to modify variables directly and efficiently avoid copying large structs.
Pointers vs Values Trade-offs
Understand when to use pointers or values in Go, weighing performance, safety, and code clarity with practical examples and decision guidelines.
Pointer Comparison
How to compare pointers in Go using equality operators, check for nil pointers, and understand the limitations and practical uses of pointer comparisons.