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

时间:2015-01-03 14:37:44

标签: interface go mgo

我有以下代码:

界面&功能定义:

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时,它可以正常工作。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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