Go Pointers Explained Simply
Published on
Contents
In Go, pointers let you refer to the memory address of a variable instead of the value directly. This is useful when you want to modify a variable inside a function or avoid copying large data structures like structs.
Key Concepts
| Symbol | Meaning | Example |
|---|---|---|
& |
Address-of operator | p := &x → pointer to x |
* |
Dereference operator | y := *p → value stored at p |
*T |
Pointer to type T |
var p *int → pointer to int |
Think in Analogies
&is like asking: “What is the address of this house?”*is like saying: “Go to this address and see what’s inside.”
Basic Pointer Example
package main
import "fmt"
func main() {
x := 10
p := &x // p holds the address of x
fmt.Println("x =", x) // Output: 10
fmt.Println("p =", p) // Output: memory address (e.g., 0xc000018030)
fmt.Println("*p =", *p) // Output: 10 (value at address)
*p = 20 // change the value at the memory address
fmt.Println("x =", x) // Output: 20
}
Modifying Values with Functions
You can pass a pointer to a function to allow it to modify the original value.
func modify(val *int) {
*val = *val + 5 // modify the value at the pointer
}
func main() {
x := 10
modify(&x) // pass the address of x
fmt.Println(x) // Output: 15
}
Summary
&x→ get the pointer (memory address) ofx*p→ access or modify the value at pointerp*T→ define a pointer to typeT(e.g.,*intfor pointer to anint)