gpt4 book ai didi

interface - 去编译错误 "undefined function"

转载 作者:数据小太阳 更新时间:2023-10-29 03:37:43 27 4
gpt4 key购买 nike

我有以下代码:

接口(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com