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.

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

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么