【问题标题】:Difference in a function implementation when instantiating an object with different function signatures实例化具有不同函数签名的对象时函数实现的差异
【发布时间】:2019-03-09 07:31:17
【问题描述】:

遇到以下不同的函数实现。示例 1 返回指针和示例 2 返回实际对象的原因是什么?

type MyInterface interface {
    Func (param int) float64 //just random signature
}

//MyInterfaceImpl implements MyInterface
type MyInterfaceImpl struct {
}

//actual implementation 
func (myObj *MyInterfaceImpl) Func(param int) float64 {
    return float64(param)
}

示例1:函数返回接口时,返回指向MyInterfaceImpl的指针

func NewMyInterface() MyInterface {
    return &MyInterfaceImpl{}
}

示例2:函数返回对象时返回MyInterfaceImpl的实际对象

func NewMyInterfaceImpl() MyInterfaceImpl {
    return MyInterfaceImpl{}
}

更新:这段代码编译并运行

func main() {
    myIf := NewMyInterface()
    fmt.Printf("Hi from inteface %f\n", myIf.Func(1000))

    myImpl := NewMyInterfaceImpl()
    fmt.Printf("Hi from impl %f\n", myImpl.Func(100))
}

UPDATE2:问题说明。

拥有func NewMyInterface() MyInterface 的声明和返回指针的return &MyInterfaceImpl{} 的有效实现这听起来很奇怪(对我来说)。我希望返回一个带有return MyInterfaceImpl{} 的 MyInterfaceImpl 对象

如果语言允许这种类型的结构,那肯定是有原因的。最终,我正在寻找以下答案:“函数声明返回一个接口。因为接口有一个属性 X,所以返回一个对象是没有意义的,但唯一有效的选项是指针”。

【问题讨论】:

  • 第一个例子你确定不是NewMyInterface() *MyInterface {
  • @lbu 更新了描述
  • What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object? 取决于他们的工作、他们的成员以及他们的使用方式。目前的例子很难说。现在,根据经验,采用接口,返回结构。阅读medium.com/@cep21/…
  • @mh-cbon 示例 1 必须返回一个指针,因为 MyInterfaceImpl 没有实现 MyInterface(尽管名称. ..) 但我同意很难说出问题所在。

标签: go


【解决方案1】:

尽管我不确定问题是关于代码的哪一部分,但让我解释一下代码的作用:

MyInterface 由具有Func(int)float64 方法的任何东西实现。
*MyInterfaceImpl 具有这样的方法。但是,MyInterfaceImpl 没有(该方法有一个指针接收器)。

NewMyInterface() 因此必须返回一个指针。 MyInterfaceImpl{} 不会实现 MyInterface

这能回答你的问题吗?


另一个问题可能是为什么调用myImpl.Func(100) 有效,尽管有上述情况。这是因为 Go 在使用指针接收器调用其方法时会自动获取接收器的地址。
对此进行了更详细的解释,例如 here

【讨论】:

  • 您能否解释一下为什么MyInterfaceImpl 没有实现MyInterface?听起来我在这里缺少基本的围棋知识。
  • spec explains it。为值类型设置的方法不包括指针接收方法。
猜你喜欢
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多