我在處理接口時遇到了問題。所以我使用 Go 包來處理我的 mongodb 東西,但我不想將該包導入到每個模型中。我想將盡可能多的子包(如模型)保留在標準庫中。所以我想我會像這樣布置一些接口:type m map[string]interface{}type collectionSlice interface { One(interface{}) error}type collection interface { Upsert(interface{}, interface{}) (interface{}, error) Find(interface{}) collectionSlice}type database interface { C(string) collection}問題是,當我去使用一個函數時:func FindItem(defindex int, d database) (*Item, error) {通過傳入我的 mgo.Database 在使用接口的包中找到:item, err := dota.FindItem(int(defindex), ctx.Database)我收到編譯器錯誤:controller/handlers.go:35: 不能在函數參數中使用 ctx.Database (type *mgo.Database) 作為 dota.database 類型:*mgo.Database 沒有實現 dota.database(C 方法的類型錯誤)有 C(string ) *mgo.Collection 想要 C(string) dota.collection我對這個概念遺漏了什么?
Golang 接口來簡化依賴關系?
慕的地8271018
2021-06-29 21:16:59