我的场景需要用户嵌入一个基本结构并实现一个接口。
然后,应该将该结构的一个实例传递给一个函数。该函数需要调用基本结构的方法。这失败了
// 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
}
沧海一幻觉
相关分类