doutuo7156 2015-05-29 11:53 采纳率: 100%
浏览 73
已采纳

如何在Golang中间接传递接口

I have a package with a method:

func Route(router *mux.Router){
    subrouter := router.PathPrefix(_API).Subrouter()
    subrouter.Path(_FOO).HandlerFunc(foo)
    subrouter.Path(_BAR).HandlerFunc(bar)
}

and I would like to remove the external dependency of mux by having a matching interface in my package that simple encompasses all the functionality used above, like so:

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)
}

but when I build this I get error:

*mux.Router does not implement api.Router (wrong type for Path method) have Path(string) *mux.Route want Path(string) api.Path

but I thought interfaces were implicitly used in golang so I thought that *mux.Route did implement my Path interface.

  • 写回答

1条回答 默认 最新

  • doulu1968 2015-05-29 12:08
    关注

    I thought interfaces were implicitly used in golang

    Values are wrapped in interfaces implicitly, but only in specific cases like when passing an implementation to a function with an interface argument:

    func X(api.Path) {}
    
    X(&mux.Route{}) // works, implicitly converted to api.Path
    

    or when returning an implementation from a function with an interface return type:

    func Y() api.Path {
        return &mux.Route{} // works, implicitly converted to api.Path
    }
    

    In your question's case the compiler wants a value that has a method with the signature:

    Path(string) api.Path
    

    But you're giving it a value with a method with signature:

    Path(string) *mux.Route
    

    As you might now, Go types are invariant. Formally:

    type A interface { Path(string) *mux.Route }
    

    is not a subtype of

    type B interface { Path(string) api.Path }
    

    Therefore this won't work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突