douyun8901 2014-07-22 17:57
浏览 23
已采纳

[Golang]使用点类型或结构类型调用指针类型的方法不同吗?

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}
  • 写回答

1条回答 默认 最新

  • duan5801 2014-07-22 18:08
    关注

    For p, calling Greeting() is simply calling p.Greeting(), for u it's calling (&u).Greeting().

    Example:

    func (u *User) Greeting() string {
        return fmt.Sprintf("Greetings %s [%p]!", u.Name, u)
    }
    
    func main() {
        p := &User{"cppgohan by pointer"}
        u := User{"cppgohan by value"}
        pu := &u
    
        fmt.Printf("[%p] %v %v
    ", pu, pu.Greeting(), pu)
        fmt.Printf("[%p] %v %v
    ", &u, u.Greeting(), u)
        fmt.Printf("[%p] %v %v
    ", p, p.Greeting(), p)
    }
    

    Output:

    [0x1030e0e0] Greetings cppgohan by value [0x1030e0e0]! &{cppgohan by value}

    [0x1030e0e0] Greetings cppgohan by value [0x1030e0e0]! {cppgohan by value}

    [0x1030e0d8] Greetings cppgohan by pointer [0x1030e0d8]! &{cppgohan by pointer}

    Notice how the first 2 have the same address because it's implicitly converted to a pointer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?