1. 程式人生 > >Gopher’s Visual Guide – Learn Go Programming

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.

`&s` and `ps` are different variables, but they all point to the same `s` variable.

Let’s run the code to understand it better.