Beginner Question: Structs, Methods, Pointers

I am going through a udemy course, and I had a question about pointers that the teacher isn’t discussing.

I understand pointers, memory addresses, and the contents thereof. I understand you might want to use a pointer if you want to modify the struct (in this case) in place, rather than modify a copy.

Refer to this code…

type person struct {
	first string
	last  string
}

func (p *person) changeMeMethod() {
	(*p).first = "Jo"
}

func changeMeFunc(p *person) {
	(*p).first = "Flem"
}

func main() {
	p := person{
		first: "Mac",
		last:  "Kam",
	}
	fmt.Println(p)
	p.changeMeMethod()
	fmt.Println(p)
	changeMeFunc(&p)
	fmt.Println(p)
}

Is there any real reason for the receiver in the changeMeMethod to refer to a pointer? Because the method is already attached to the struct, there’s no copying of value.

Am I correct in thinking here?

In Go, we don’t use a special name like this or self for the receiver, we choose receiver names as we would for any parameter.

Using receiver as Pointer to avoid copying values, it is used when it is necessary to update the receiver variable, or to avoid copying values, we use the address of the variable using the pointer

otherwise:

type person struct {
	first string
	last  string
}

func (p person) changeMeMethod() {
	p.first = "Jo"
}

func changeMeFunc(p person) {
	p.first = "Flem"
}

func main() {
	p := person{
		first: "Mac",
		last:  "Kam",
	}
	fmt.Println(p)
	p.changeMeMethod()
	fmt.Println(p)
	changeMeFunc(p)
	fmt.Println(p)
}

// Output:
// {Mac Kam}
// {Mac Kam}
// {Mac Kam}

https://play.golang.org/p/2Pdlv2IOxZD

with Pointer

type person struct {
	first string
	last  string
}

func (p *person) changeMeMethod() {
	p.first = "Jo"
}

func changeMeFunc(p *person) {
	p.first = "Flem"
}

func main() {
	p := person{
		first: "Mac",
		last:  "Kam",
	}
	fmt.Println(p)
	p.changeMeMethod()
	fmt.Println(p)
	changeMeFunc(&p)
	fmt.Println(p)
}
// Output:
// {Mac Kam}
// {Jo Kam}
// {Flem Kam}

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