2015-05-29 50 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 } 

亞型所以這是不行的。