亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

去編譯錯誤“未定義的函數”

去編譯錯誤“未定義的函數”

Go
RISEBY 2021-09-10 16:51:52
我有以下幾段代碼:接口及功能定義:package helperimport "gopkg.in/mgo.v2/bson"// Defines an interface for identifiable objectstype Identifiable interface {    GetIdentifier() bson.ObjectId}// Checks if a slice contains a given object with a given bson.ObjectIdfunc IsInSlice(id bson.ObjectId, objects []Identifiable) bool {    for _, single := range objects {        if single.GetIdentifier() == id {            return true        }    }    return false}滿足“可識別”的用戶結構的定義:package modelsimport (    "github.com/my/project/services"    "gopkg.in/mgo.v2/bson")type User struct {    Id       bson.ObjectId   `json:"_id,omitempty" bson:"_id,omitempty"`    Username string          `json:"username" bson:"username"`    Email    string          `json:"email" bson:"email"`    Password string          `json:"password" bson:"password"`    Albums   []bson.ObjectId `json:"albums,omitempty" bson:"albums,omitempty"`    Friends  []bson.ObjectId `json:"friends,omitempty" bson:"friends,omitempty"`}func GetUserById(id string) (err error, user *User) {    dbConnection, dbCollection := services.GetDbConnection("users")    defer dbConnection.Close()    err = dbCollection.Find(bson.M{"_id": bson.ObjectIdHex(id)}).One(&user)    return err, user}func (u *User) GetIdentifier() bson.ObjectId {    return u.Id}檢查切片內對象是否存在的測試:package controllersimport (     "github.com/my/project/helper"    "gopkg.in/mgo.v2/bson")var testerId = bson.NewObjectId()var users = []models.Users{}/* Some code to get users from db */if !helper.IsInSlice(testerId, users) {    t.Fatalf("User is not saved in the database")}當我嘗試編譯測試時,我收到錯誤:undefined helper.IsInSlice. 當我重寫IsInSlice方法以不采取[]Identifiable但[]models.User它工作正常。有任何想法嗎?
查看完整描述

2 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

您的問題是您試圖將 type[]models.Users{}的值用作type的值[]Identifiable。當models.Usersimplements 時Identifiable,Go 的類型系統被設計成實現接口的值的切片不能用作(或轉換為)接口類型的切片。

有關更多詳細信息,請參閱 Go 規范關于轉換部分。


查看完整回答
反對 回復 2021-09-10
  • 2 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號