Gopherâs Visual Guide â Learn Go Programming
Pass-by-value and the pointers
Below func accepts a pointer to a string variable. It changes the value the ps pointer points to. Then it will try to set the passed pointerâs value to nil. So, the pointer will not point to the passed string variableâs address anymore.
func pass(ps *string) { *ps = "donald" ps = nil}
We define a new variable s and then we take its address by using the ampersand operator and store its address inside a new pointer variable: ps.
s := "knuth"ps := &s
Letâs pass ps to the pass func.
pass(ps)
After the func ends, we see that the value inside the s variable has changed. But, the ps pointer still points to a valid address of the s variable
// Output: // s : "donald" // ps: 0x1040c130
The ps pointer is passed-by-value to the pass func, only the address it points to get copied to a new pointer variable inside the pass func. So, setting it to nil inside the func had no effect on the passed pointerâs value.
Letâs run the code to understand it better.