Regarding pointers. 4hrs only experience


(BobP) #1
package main

import "fmt"

type person struct {
	firstName string
	lastName  string
}

func printPerson(p person) {
	fmt.Println(p)
}
func (pointerToPerson *person) updatePerson(newFirstName string) {
	newPerson := *pointerToPerson
	fmt.Println(newPerson)
	newPerson.firstName = newFirstName
	fmt.Println(newPerson)
}

func main() {
	bobuGeorge := person{"Bobu", "George"}
	bobuGeorge.updatePerson("Bob")
	printPerson(bobuGeorge)

}

Why is the original ‘person’ not getting updated?
if i use (*pointerToPerson), the original person gets updated


(Johan Dahl) #2

Hi

Structures is normally passed by value. So your line:

newPerson := *pointerToPerson

make a new struct of type Person which is a copy of the Person pointed to by pointerToPerson

I simple way to “fix” your program is to make the line into

newPerson := pointerToPerson

Which means create a new pointer to person and make it to point to the same struct as pointerToPerson


(Lutz Horn) #3

updatePerson is a method on a person, pointerToPerson is the receiver of this method.

The expected behaviour of a method that manipulates the receiver is to do this directly:

func (pointerToPerson *person) updatePerson(newFirstName string) {
	pointerToPerson.firstName = newFirstName
}

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