2015-05-29 54 views
-1

我有一个封装的方法:如何通过接口间接golang

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

,我想通过在我的包的匹配接口,简单涵盖所有功能以除去多路复用器的外部的依赖上面使用,就像这样:

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

,但我认为接口隐式在golang中使用,所以我认为*mux.Route确实实现了我的Path接口。

回答

5

I thought interfaces were implicitly used in golang

值被包裹在隐式的,但仅在特定情况下的接口传递时的功能的实现与接口的参数,如:

func X(api.Path) {} 

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

或从功能与接口返回的实现时返回类型:

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

在你的问题的情况下,编译要具有与签名的方法的值:

Path(string) api.Path 

但是你用签名的方法给它一个值:

Path(string) *mux.Route 

正如你可能现在去类型是不变的。形式上:

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

不是

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

亚型所以这是不行的。