我的场景需要用户嵌入一个基本结构并实现一个接口。然后,应该将该结构的一个实例传递给一个函数。该函数需要调用基本结构的方法。这失败了// Given base struct and interfacetype 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 functioninst := CustomStruct{}SomePackageFun(&inst)// The below function receives the custom struct, and must call the base struct's method, but this failsfunc 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}
1 回答
沧海一幻觉
TA贡献1824条经验 获得超5个赞
如果您希望能够在接口类型的变量上调用方法,则应将该方法添加到接口中。出于满足接口的目的,来自嵌入式结构的方法计数。要调用不属于接口的任何内容,您必须对具体类型(或具有该方法的不同接口类型)进行断言,这违背了这一点。
- 1 回答
- 0 关注
- 89 浏览
添加回答
举报
0/150
提交
取消