Regarding pointers. 4hrs only experience

package main

import "fmt"

type person struct {
	firstName string
	lastName  string

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

func main() {
	bobuGeorge := person{"Bobu", "George"}


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


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

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

1 Like

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