interface - 去编译错误 "undefined function"

标签 interface go mgo

我有以下代码:

接口(interface)&功能定义:

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
}

检查 slice 内对象是否存在的测试:

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 的类型系统的设计使得实现接口(interface)的值 slice 不能用作(或转换为)接口(interface)类型的 slice 。

请参阅 Go 规范的 section on conversions了解更多详情。

关于interface - 去编译错误 "undefined function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27755954/

相关文章:

docker - 静态链接去二进制上没有可访问的服务器

java - 在嵌套枚举实现接口(interface)中继承泛型类型

java - 使用枚举内部的接口(interface)

golang源码为什么要这样写

java - 接口(interface)类型转换困境

go - 追加多值返回到func参数

go - 来自 Go 的不区分大小写的 MongoDB 查询

go - 将提取的 tar.gz 复制到单个文件

go - 第一次设置 go-swagger

mongodb - 如何将 mongodb 投影与 Go 和 mgo 一起使用?