Like the title said, I don't know the different when I use the struct type or pointer type when call the method Greeting()
in my case, does the call p.Greeting()
and u.Greeting()
just same? Seems no performance different either, when call the Greeting()
method.
I think u.Greeting()
is automatically convert to (&u).Greeting()
?
Everything in Go is passed by value, but I think in this case, the caller u
is passing by reference or pointer.
package main
import "fmt"
type User struct {
Name string
}
func (u *User) Greeting() string {
u.Name = u.Name+" modify"
return fmt.Sprintf("Greetings %s!", u.Name)
}
func main() {
p := &User{"cppgohan by pointer"}
u := User{"cppgohan by value"}
fmt.Println(p.Greeting(), p)
fmt.Println(u.Greeting(), u)
}
Output:
Greetings cppgohan by pointer modify! &{cppgohan by pointer modify}
Greetings cppgohan by value modify! {cppgohan by value modify}