我有以下幾段代碼:接口及功能定義: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 回答
- 0 關注
- 197 瀏覽
添加回答
舉報
0/150
提交
取消