You have a juice box. 🍹
You give your friend a copy of it.
If they finish theirs, yours is still full.
But what if you just gave them your juice box directly?
If they drink it… it’s gone. 😢
That’s the difference between:
Copying a value
Sharing the original value (via a pointer)
In Go, a pointer is like an arrow ➡️ that points to the original value in memory.
Instead of copying data, you’re saying:
“Here’s the address of the real thing.”
num := 10
ptr := &num // `&` gets the addressNow ptr is a pointer to num.
To see what it's pointing to:
fmt.Println(*ptr) // Output: 10That *ptr means:
“Go to the address and give me the value.”
*ptr = 20
fmt.Println(num) // Output: 20You changed the original value by updating it through the pointer!
Let’s say you write a function:
func double(x int) {
x = x * 2
}And call:
num := 5
double(num)
fmt.Println(num) // Output: 5 ❌ (didn’t change!)It didn’t change because Go passed a copy of num.
✅ Fix with a pointer:
func double(x *int) {
*x = *x * 2
}
num := 5
double(&num)
fmt.Println(num) // Output: 10 ✅To avoid copying big data (like big structs or arrays)
To change values inside functions
To share values between places in your program
Go doesn’t allow pointer arithmetic (unlike C)
You can’t create a pointer to a constant or expression
Go has garbage collection — so you don’t worry about freeing memory
&xmeans: “Give me the address of x”*ptrmeans: “Give me the value at that address”Use pointers to change values and avoid unnecessary copies
Common in structs, functions, and method receivers
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.