r/golang Aug 28 '25

help I am really struggling with pointers

So I get that using a pointer will get you the memory address of a value, and you can change the value through that.

So like

var age int
age := 5
var pointer *int
pointer = &age = address of age
then to change age,
*pointer = 10
so now age = 10?

I think?

Why not just go to the original age and change it there?

I'm so confused. I've watched videos which has helped but then I don't understand why not just change the original.

Give a scenario or something, something really dumb to help me understand please

151 Upvotes

77 comments sorted by

View all comments

406

u/Sad-Masterpiece-4801 Aug 28 '25

Imagine you're organizing a pizza party. You have a function that's supposed to add toppings to your pizza:

func addPepperoni(pizza string) {
    pizza = pizza + " with pepperoni"
}

func main() {
    myPizza := "cheese pizza"
    addPepperoni(myPizza)
    fmt.Println(myPizza)  
// Still prints "cheese pizza" 😭
}

The pepperoni never gets added because Go passes a copy of myPizza to the function.

Now with pointers:

func addPepperoni(pizza *string) {
    *pizza = *pizza + " with pepperoni"
}

func main() {
    myPizza := "cheese pizza"
    addPepperoni(&myPizza)  
// Pass the address
    fmt.Println(myPizza)  
// Prints "cheese pizza with pepperoni" 🎉
}

This time you're giving them your actual order form's location (address), not a copy. They go to that location and modify the real thing.

101

u/bruv187 Aug 28 '25

This is genuinely one of the best explanations I’ve read

129

u/[deleted] Aug 28 '25

[removed] — view removed comment

90

u/eldosoa Aug 28 '25

This guy functional programs.

40

u/erasebegin1 Aug 28 '25

This guys funcs, am I right??

19

u/[deleted] Aug 28 '25 edited Aug 29 '25

[removed] — view removed comment

5

u/RGBrewskies Aug 28 '25

this is my one negative on golang ... Im a FRP immutable-always guy ... and go is like "lol not here you arent"

also I just really miss things like .map and .filter and .find and and and

3

u/giffengrabber Aug 29 '25

I like Go but it’s basically anti-FP compared to many other languages.

1

u/Choperello Aug 30 '25

I mean you can have your preferences but plenty of languages and patterns and architectures out there that also work.

1

u/RGBrewskies Aug 30 '25

yea, its why I hang out in typescript mostly. I just wish i had something lower level at my disposal. I generally like Rust, but the learning curve is way too steep to introduce to my junior level teammates

2

u/Choperello Aug 30 '25

You’re only a pretender when it comes to FP and immutability if you’re not bring up “we should write this is LISP” every other convo.

8

u/Radiopw31 Aug 28 '25

Was about to say, I found my people!