【发布时间】:2020-05-10 16:53:41
【问题描述】:
我的场景需要用户嵌入一个基本结构并实现一个接口。
然后,应该将该结构的一个实例传递给一个函数。该函数需要调用基本结构的方法。这失败了
// Given base struct and interface
type Interface interface {
Do()
}
type BaseStruct struct {
i int
s string
}
func (*b BaseStruct) Stuff() {}
// The user needs to create a struct that embeds BaseStruct and to implement Interface:
type CustomStruct struct {
*BaseStruct
}
func (*c CustomStruct) Do() {}
// The user now instantiates the struct and needs to call a function
inst := CustomStruct{}
SomePackageFun(&inst)
// The below function receives the custom struct, and must call the base struct's method, but this fails
func SomePackageFunc(i Interface) {
// declaring the function with Interface works but I can't call the methods of BaseStruct
i.Stuff() // not recognized by the compiler
}
【问题讨论】:
-
func SomePackageFunc(a Interface)。如果*CustomStruct实现了Interface,你就不能用它来调用 SomePackageFunc。请注意,您似乎尝试了类似继承的东西:它不起作用。 -
感谢您的回复。我会在问题中添加更多细节。我的问题是该函数需要调用用户对象中基本结构的一个方法,但是它抛出了异常
-
我不知道你想做什么,怎么做以及为什么。