【发布时间】: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