去编译错误"undefined function"

Go compile error "undefined function"

我有以下几段代码:

接口&功能定义:

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
}

用户结构体定义满足'Identifiable':

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

有什么想法吗?

您的问题是您试图将类型 []models.Users{} 的值用作类型 []Identifiable 的值。虽然 models.Users 实现了 Identifiable,但 Go 的类型系统的设计使得实现接口的值切片不能用作(或转换为)接口类型的切片。

有关详细信息,请参阅 Go 规范的 section on conversions

显然,Go 没有重建我的包,而是在旧版本中寻找函数。因此它是未定义的。执行 rm -fr [GO-ROOT]/pkg/github.com/my/project/models 成功了。