doucai6663 2018-12-11 10:27
浏览 46
已采纳

结构的方法签名之间的区别

As a programmer coming from other languages like C++, I find it rather strange that go allows to specify methods for structs that allow either a pointer or an instance as a parameter. According to go by example once could use either of them if we didn't want to modify the origin:

Go automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on method calls or to allow the method to mutate the receiving struct.

Consider the following code:

package main

import (
    "fmt"
)

type Foo struct {}

type Bar struct {}

func (this Foo) String() string {
  return "Foo"
}

func (this *Bar) String() string {
  return "Bar"
}

func main() {
  fmt.Println(Foo{}) // "Foo"
  fmt.Println(Bar{}) // "{}"
}

Why can't I use both signature versions to modify the stringify (I don't know how it is actually called in go) behavior of the structs?

Just to be clear: I don't really care about the stringify, but want to understand how the language behaves.

  • 写回答

2条回答 默认 最新

  • dqhdpppm02183 2018-12-11 10:38
    关注

    Just add & to the Bar{} and make it pointer receiver, like this:

    fmt.Println(&Bar{}) // "Bar"
    

    Here a little adjustment to your code that outputs:

    Foo
    Bar
    

    see:

    package main
    
    import "fmt"
    
    type Foo struct{}
    
    func (Foo) String() string {
        return "Foo"
    }
    
    type Bar struct{}
    
    func (*Bar) String() string {
        return "Bar"
    }
    
    func main() {
        fmt.Println(Foo{}) // "Foo"
        pb := &Bar{}
        fmt.Println(pb) // "Bar"
    }
    

    Notes:

    Receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"

    And you don't need names here for your example.

    And nice to read Golang methods receivers:

    Value receivers operate on a copy of the original type value. This means that there is a cost involved, especially if the struct is very large, and pointer received are more efficient.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序