RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 12: Pointers in Go – How to Share and Change Values Without Copying 📌🧷

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

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 address

Now ptr is a pointer to num.

To see what it's pointing to:

fmt.Println(*ptr) // Output: 10

That *ptr means:

“Go to the address and give me the value.”

*ptr = 20
fmt.Println(num) // Output: 20

You 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

  • &x means: “Give me the address of x”

  • *ptr means: “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

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.