2

I have the following struct and :

type Person struct {
    Name    string
}


steve := Person{Name: "Steve"}

Can you explain how the following 2 methods (one without the pointer and one with in the receiver) both are able to print the p.Name?

func (p *Person) Yell() {
    fmt.Println("Hi, my name is", p.Name)
}

func (p Person) Yell(){
    fmt.Println("YELLING MY NAME IS", p.Name)
}

steve.Yell()

Wouldn't the Name not exist when pointing straight to the Person (not the instance steve?)

1 Answer 1

4

Both point to the instance, however (p Person) points to a new copy every time you call the function, where (p *Person) will always point to the same instance.

Check this example :

func (p Person) Copy() {
    p.Name = "Copy"
}

func (p *Person) Ptr() {
    p.Name = "Ptr"
}

func main() {
    p1, p2 := Person{"Steve"}, Person{"Mike"}
    p1.Copy()
    p2.Ptr()
    fmt.Println("copy", p1.Name)
    fmt.Println("ptr", p2.Name)
}

Also read Effective Go, it's a great resource to the language.

Sign up to request clarification or add additional context in comments.

2 Comments

so i assume that if the method changed the value of p.Name then it would change the original 'steve' but if I change the value of Name in the (p Person) version I am changing something that will be immediately not accessible since I don't have a handle on the copy?
Just as a note, there is a performance difference when calling a method by value. It may or may not be significant depending on the size of your structure or how often the methods are called, but it's something to consider :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.