我有一个程序正在尝试在“子类”上实现功能,其中父类可以检查接口是否已实现。从角度上看,它真正处理基于方法存在与否的REST URL生成。
我遇到的问题是,根据以下模式,在TestController对象上找到了IList和IGet界面,而只有1个被实现。当调用IGet接口时,我会遇到恐慌。
我宁愿不对基础结构中的Get/List进行具体定义,然后再覆盖它们,而是更喜欢测试其是否存在,然后再执行操作。
这里还有一个go playground链接:https://play.golang.org/p/5j58fejeJ3
我遇到的问题是,根据以下模式,在TestController对象上找到了IList和IGet界面,而只有1个被实现。当调用IGet接口时,我会遇到恐慌。
我宁愿不对基础结构中的Get/List进行具体定义,然后再覆盖它们,而是更喜欢测试其是否存在,然后再执行操作。
这里还有一个go playground链接:https://play.golang.org/p/5j58fejeJ3
package main
import "fmt"
type IGet interface {
Get(int)
}
type IList interface {
List(int)
}
type Application struct {
name string
}
type BaseAppController struct {
*Application
IGet
IList
}
type TestController struct {
*BaseAppController
}
func (ctrl *BaseAppController) Init() {
fmt.Println("In Init")
if f, ok := interface{}(ctrl).(IGet); ok {
fmt.Println("Controller Found GET", f)
} else {
fmt.Println("Controller NOT Found GET", f)
}
if f, ok := interface{}(ctrl).(IList); ok {
fmt.Println("Controller Found LIST", f)
} else {
fmt.Println("Controller NOT Found LIST", f)
}
}
func (ctrl *BaseAppController) Call() {
fmt.Println("In Call")
if f, ok := interface{}(ctrl).(IGet); ok {
fmt.Println("Controller Found GET - going to call", f)
f.Get(7)
} else {
fmt.Println("Controller NOT Found GET - can't call", f)
}
}
// Test controller implements the Get Method
func (ctrl *TestController) Get(v int) {
fmt.Printf("Hi name=%s v=%d\n", ctrl.name, v)
}
func main() {
app := Application{"hithere"}
ctrl := TestController{&BaseAppController{Application: &app}}
ctrl.Init()
ctrl.Call()
}