给定下面的伪代码:
type(
MyStruct struct {
AFunction func(string) ([]byte, error)
}
MyInterface interface {
AFunction(string) ([]byte, error)
}
)
func NeedThis(s string) ([]byte, error){
//relevant function stuff
}
m := &MyStruct{AFunction: NeedThis}
问题出现了,m不满足MyInterface接口(interface);我多少能明白为什么会这样。有没有一种方法可以将函数附加到结构,使得构造的结构满足接口(interface),而无需在结构上实际构建定义方法?我对此有一些模糊/错误的推理,也许有助于为我澄清这一点,或者展示一种更好的方法来推理这种情况。
最佳答案
你能不能在 MyStruct
上定义一个方法 AFunction
来分派(dispatch)到存储的 AFunction
函数指针?如果你有很多这样的东西并不理想,但我认为它可以完成这项工作?
即像
func (s MyStruct) AFunction(str string) ([]byte, error) {
return s.AFunction(str)
}
edit: 以上可能会导致编译器出错,因为 s.AFunction
是不明确的,所以你可能不得不给它们(方法和函数指针)不同的名字,但它应该给正确的想法。
关于结构初始化以满足没有显式方法定义的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292546/