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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?