go - 如何在golang中间接传递接口(interface)

标签 go

我有一个带有方法的包:

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/

相关文章:

linux - 为什么这个 twurl 命令(在 linux 上运行,由 golang exec 运行)没有经过身份验证?

go - 使用 mgo.Marshal() 编码指针

oop - 是否有任何不是用c++,rust或ada编写的语言?

mysql - 避免循环 - 递归 m2m 关系自引用

Golang 结构定义模式

encryption - Golang AES ECB 加密

docker - 云运行和发布容器

go - grpc protobuf 使用字符串创建新结构

go - 可以存储多种类型但没有共享功能的变量

go - 在 Go 中查找隐藏的矿工(隐藏窗口 + 命令行)