Reputation: 5323
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?)
Upvotes: 2
Views: 862
Reputation: 99225
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.
Upvotes: 4