Hands on exercise using a pointer and dereferencing

https://play.golang.org/p/L5y0DirzyvK

Why here , “changeMe(&p1)” , do we call the pointer? What is the reason and/or purpose?

1 Like

Because the function accepts a pointer in order to be able to modify the variable it points to. As you’ve been told in other topics, in Go parameters are passed by value, that is the function gets a copy of whatever you pass to it and thus any local modification inside the function won’t affect the original variable. So to be able to modify a variable we pass a pointer to it, i.e. it’s address, because then the function can dereference the pointer and get the original variable and change it.

Look at this slightly modified example based on yours where I added a function that accepts a person instead of a pointer to one and see how it doesn’t modify p1 when called, whereas your original function does: https://play.golang.org/p/TNMag0Nvved

3 Likes

“passed by value, that is the function gets a copy of whatever you pass to it and thus any local modification inside the function won’t affect the original variable. So to be able to modify a variable we pass a pointer to it, i.e. it’s address, because then the function can dereference the pointer and get the original variable and change it.”

That makes perfect sense. We were told by the teacher that everything in Go is “passed by value”, but we were not given a definition of that concept, and I had no idea what it meant or how to ask. So you may be sure that I’ll save this information. I am a person who needs words and concepts specifically defined.

Also, a very interesting and helpful modification.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.