dpvm7231 2019-03-08 21:38
浏览 14
已采纳

实例化具有不同功能签名的对象时,功能实现上的差异

Came across the following differences a function implementations. What is the reasoning behind Example 1 returning a pointer and Example 2 returning an actual object?

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)
}

Example 1: the pointer to the MyInterfaceImpl is returned when function returns an interface

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

Example 2: actual object of MyInterfaceImpl is returned when function returns the object

func NewMyInterfaceImpl() MyInterfaceImpl {
    return MyInterfaceImpl{}
}

UPDATE: This piece of code compiles and runs

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

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

UPDATE2: Question clarification.

This sounds weird (for me) to have a declaration of func NewMyInterface() MyInterface and a valid implementation of return &MyInterfaceImpl{} where a pointer is returned. I would expect to return an object of MyInterfaceImpl with return MyInterfaceImpl{}

If the language allows such types of constructs, there must be a reason for that. Eventually, I am looking for a following answer: "The function declaration returns an interface. Because the interface has a property X it is does not make sense to return an object, but the only valid option is a pointer".

  • 写回答

1条回答 默认 最新

  • douzhong5902 2019-03-08 23:09
    关注

    Even though I'm not sure which part of the code the question is about, let me explain what the code does:

    MyInterface is implemented by anything having a Func(int)float64 method.
    *MyInterfaceImpl has such a method. However, MyInterfaceImpl does not (the method has a pointer receiver).

    NewMyInterface() thus has to return a pointer. MyInterfaceImpl{} wouldn't implement MyInterface.

    Does this answer your question?


    Another question might be why the call myImpl.Func(100) works, despite the above. This is because Go automatically takes the address of the receiver when calling its methods with pointer receivers.
    This is explained in more detail for example here.

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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?