猿问

去编译错误“未定义的函数”

我有以下几段代码:


接口及功能定义:


package helper


import "gopkg.in/mgo.v2/bson"


// Defines an interface for identifiable objects

type Identifiable interface {

    GetIdentifier() bson.ObjectId

}


// Checks if a slice contains a given object with a given bson.ObjectId

func IsInSlice(id bson.ObjectId, objects []Identifiable) bool {

    for _, single := range objects {

        if single.GetIdentifier() == id {

            return true

        }

    }

    return false

}

满足“可识别”的用户结构的定义:


package models


import (

    "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 controllers


import ( 

    "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它工作正常。


有任何想法吗?


RISEBY
浏览 177回答 2
2回答

慕神8447489

您的问题是您试图将 type[]models.Users{}的值用作type的值[]Identifiable。当models.Usersimplements 时Identifiable,Go 的类型系统被设计成实现接口的值的切片不能用作(或转换为)接口类型的切片。有关更多详细信息,请参阅 Go 规范关于转换的部分。
随时随地看视频慕课网APP

相关分类

Go
我要回答