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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?