1 回答

TA貢獻1796條經驗 獲得超10個贊
您走在正確的軌道上,但是與接口相關的代碼中存在一些錯誤。
為了讓結構實現你的storage接口,它需要一個帶有簽名的方法AccountExists(id int64)。根據規范(https://godoc.org/github.com/jmoiron/sqlx#DB)sqlx.Db沒有具有此簽名的方法。
你需要做的是這樣的:
package database
func NewMyDB() (*MyDB, error) {
dbConnection := // get an *sqlx.DB instance
return &MyDB{db: dbConnection}, nil
}
type MyDB struct {
db *sqlx.DB
}
func (db *MyDB) AccountExists(id int64) {
// query db here
}
控制器:
type storage interface {
AccountExists(id int64)
}
type API struct {
db storage
}
func NewAPI(db storage) (*API, error) {
return &API{db}, nil
}
注意幾件事。1. 以前,您的NewMyDB構造函數返回的是結構的實例sqlx.DB而不是結構的實例(我將其重命名為MyDB避免與sqlx.DB類混淆)。2.以前你的MyDB結構沒有帶有簽名的方法 AccountExists(id int64)。因此它沒有實現storage,因為storage需要這個方法。
我建議閱讀一些關于接口如何在 Golang 中工作的內容。我認為這對解決您的問題有很大幫助。這是一個您可以快速閱讀的鏈接(其中包括另一個指向更長但有用的博客文章的鏈接):https ://gobyexample.com/interfaces
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報