我有一个带有方法的包:
func Route(router *mux.Router){
subrouter := router.PathPrefix(_API).Subrouter()
subrouter.Path(_FOO).HandlerFunc(foo)
subrouter.Path(_BAR).HandlerFunc(bar)
}
我想通过在我的包中有一个匹配的接口(interface)来删除 mux 的外部依赖性,该接口(interface)简单地包含上面使用的所有功能,如下所示:
type Router interface{
Path(string) Path
PathPrefix(string) Path
}
type Path interface{
HandlerFunc(http.HandlerFunc)
Subrouter() Router
}
func Route(router Router){
subrouter := router.PathPrefix(_API).Subrouter()
subrouter.Path(_FOO).HandlerFunc(foo)
subrouter.Path(_BAR).HandlerFunc(bar)
}
但是当我构建它时出现错误:
*mux.Router does not implement api.Router (wrong type for Path method) have Path(string) *mux.Route want Path(string) api.Path
但我认为接口(interface)在 golang 中隐式使用,所以我认为 *mux.Route
确实实现了我的 Path 接口(interface)。
最佳答案
I thought interfaces were implicitly used in golang
值隐式包装在接口(interface)中,但仅在特定情况下,例如将实现传递给具有接口(interface)参数的函数时:
func X(api.Path) {}
X(&mux.Route{}) // works, implicitly converted to api.Path
或者当从具有接口(interface)返回类型的函数返回实现时:
func Y() api.Path {
return &mux.Route{} // works, implicitly converted to api.Path
}
在您的问题中,编译器需要一个具有签名方法的值:
Path(string) api.Path
但是你用带有签名的方法给它一个值:
Path(string) *mux.Route
正如您现在可能看到的,Go 类型是不变的。正式地:
type A interface { Path(string) *mux.Route }
不是
的子类型type B interface { Path(string) api.Path }
因此这行不通。
关于go - 如何在golang中间接传递接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528941/