接口定义内方法签名中的接口

我想要这样的东西:


type MyInterface interface {

    MyMetod(interface{})

}

并拥有类型


type MyType struct {}

用方法


func (mt *MyType) MyMethod(SomeConcreteType) {

   // body

}

实现MyInterface。


但似乎 Go 无法处理这个问题。我收到一个错误,说它有MyMethod(SomeConcreteType)但它想要MyMethod(interface{})。为什么会这样,什么是解决这个问题的好方法?


摇曳的蔷薇
浏览 181回答 1
1回答

慕盖茨4494581

为什么是这样?这是语言设计。解决方案是匹配接口:type MyType struct{}func (mt *MyType) MyMethod(v interface{}) {    v, ok := v.(SomeConcreteType)    if !ok {        panic("!ok")    }    v.doStuff()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go