Go (Golang) is a powerful, statically typed language built for simplicity, performance, and scalability. One of the key features that sets Go apart from many high-level languages is its support for pointers, which allow you to directly reference memory addresses.
In this blog, youβll learn everything you need to know about pointers in Go β from what they are and why they matter, to how theyβre used in real-world applications.
π What is a Pointer?
A pointer is a variable that holds the memory address of another variable.
π Analogy:
Think of a variable as a house and its value as a person living inside. A pointer is like the houseβs address written on a note. You donβt carry the person β you carry the address.
π§ͺ Basic Pointer Syntax in Go
var x int = 10
var p *int = &x
-
xis anintvariable. -
&xgives the memory address ofx. -
pis a pointer to int (*int) that stores that address.
π Dereferencing
To get the value stored at the pointer address:
fmt.Println(*p) // Output: 10
βοΈ Why Use Pointers?
- π Avoid copying large values (performance gain).
- π§ Modify values inside functions.
- βοΈ Work with dynamic data structures (like linked lists, trees).
- π Share state between functions or goroutines.
π§βπ» Example: Modify Value via Pointer
func update(val *int) {
*val = 99
}
func main() {
num := 50
update(&num)
fmt.Println(num) // Output: 99
}
β
*val = 99 changes the original num since we're working with its memory address.
π Value vs Pointer
| Feature | Value (Copy) | Pointer (Reference) |
|---|---|---|
| Memory usage | More (copies value) | Less (copies address) |
| Modify original? | β No | β Yes |
| Performance | Slower with large data | Faster |
π The new() Keyword
ptr := new(int)
*ptr = 77
fmt.Println(*ptr) // Output: 77
-
new(int)allocates memory for anintand returns a pointer to it. - The pointerβs default value is zero.
π€ Pointers with Structs
type User struct {
Name string
}
func rename(u *User) {
u.Name = "Alice"
}
func main() {
user := User{Name: "Bob"}
rename(&user)
fmt.Println(user.Name) // Output: Alice
}
β Modifications inside the function persist outside because we pass a pointer.
π§ Common Pitfalls
- β Dereferencing a nil pointer
var p *int
fmt.Println(*p) // panic: runtime error: invalid memory address
- β
Always check for
nil:
if p != nil {
fmt.Println(*p)
}
π Passing by Value vs Pointer (Recap)
| Case | Use Pointer? |
|---|---|
| Modify original data | β Yes |
| Pass large structs | β Yes |
| Read-only small values | β No |
π Conclusion
Pointers are a core concept in Go that unlock performance, control, and flexibility. By mastering pointers, you gain a deeper understanding of how data flows and memory works under the hood β critical skills for any serious Go developer.
β¨ Remember: With great power (pointers), comes great responsibility (memory safety)!
Top comments (1)
DON'T Dereferencing a NOT nil pointer