Changing a pointer

Changing a pointer

When a function does not have a return value, it does not mean, that you can get no information back from the function. With a pointer it is possible to change a value:

  1 package main
  2
  3 import (
  4         "fmt"
  5 )
  6
  7 func main() {
  8         hello := "hello"
  9         msg := &hello
 10         fmt.Println("Say ")
 11         unchangedSay(msg)
 12         fmt.Println("Unchanged: ",*msg)
 13         changedSay(msg)
 14         fmt.Println("Changed: ",*msg)
 15 }
 16
 17 func unchangedSay(parm *string) {
 18         goodbye := "Wave goodbye"
 19         parm = &goodbye
 20 }
 21 func changedSay(parm *string) {
 22         goodbye := "Wave goodbye"
 23         *parm = goodbye
 24 }
package main

import (
	"fmt"
)

func main() {
	hello := "hello"
	msg := &hello
	fmt.Println("Say ")
	unchangedSay(msg)
	fmt.Println("Unchanged: ",*msg)
	changedSay(msg)
	fmt.Println("Changed: ",*msg)
}

func unchangedSay(parm *string) {
	goodbye := "Wave goodbye"
	parm = &goodbye
}
func changedSay(parm *string) {
	goodbye := "Wave goodbye"
	*parm = goodbye
}

Why does unchangedSay does not change msg and changedSay does?

sequenceDiagram participant msg participant "Hello" msg-->>"Hello": point to

In line 9 the variable msg, which has the scope in the function main is assigned to an memory address. So printing the pointer itself with fmt.Println(msg) gives for example 0xc000096210.

Not changing data

With the call to unchangedSay(msg) in line 11, this value 0xc000096210 is copied to the function parameter parm.

Then inside unchangedSay in line 19, only the value of the local pointer variable parm is changed.

sequenceDiagram participant parm participant "Hello" participant "Wave goodbye" parm-->>"Hello": poinst to parm -->> "Wave goodbye" : points to

Changing Data

To change the value “hello” to “Wave goodbye”, in line 23 :

 *parm = goodbye
sequenceDiagram participant parm participant "Hello" parm-->>"Hello": points to ChangedSay() -->> "Hello" : overwrite with "Wave goodbye"

This overrides the string which is stored at the memory location 0xc000096210 (in the example). Changing strings that way is not recommended, its just just for learning purposes here

Source

See the full source on github.

Sources