简体   繁体   中英

golang method pointer to receiver

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?)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM