gpt4 book ai didi

go - 返回的接口(interface){}类型断言

转载 作者:IT王子 更新时间:2023-10-29 02:28:19 26 4
gpt4 key购买 nike

我需要查询数据库的函数。

我使用 github.com/gocraft/dbr,所以我创建了辅助函数:

//SelectData - selects data from database
func SelectData(table, fields, where string, data interface{}) interface{} {

var ptr reflect.Value

ptr = reflect.New(reflect.TypeOf(data)) // create new pointer

obj := ptr.Interface()

sess := Session

query := sess.Select(fields).
From(table)

if len(where) > 0 {
query.Where(where)
}

_, err := query.Load(obj)

if err != nil {
panic(err)
}

return obj

}

然后我尝试使用它:

//CheckUser - checks is user registered in db
func CheckUser(userid string) User {
var user User
var i interface{}

i = db.SelectData("users", "*", "", user)

fmt.Printf("=%#v \n", i)

user = i.(User)
return user
}

但是我得到了运行时错误:

interface conversion: interface {} is *models.User, not models.User
D:/Go/src/runtime/panic.go:513 (0x42ccb6)
gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
D:/Go/src/runtime/iface.go:248 (0x4091ac)
panicdottypeE: panic(&TypeAssertionError{iface, have, want, ""})
C:/Users/vasalt/go/src/wcenter/models/model_user.go:29 (0x9dda3a)
CheckUser: user = i.(User)
C:/Users/vasalt/go/src/wcenter/controllers/ctrl_main.go:59 (0x9e03b6)
SetPageData: fmt.Printf("=result = %#v\n", models.CheckUser("1234"))

调试输出:

=&models.User{UID:sql.NullString{String:"1", Valid:true}, UserID:sql.NullString{String:"1234", Valid:true}, UserGroup:sql.NullString{String:"1", Valid:true}}

所以它成功地从数据库中检索数据,但它返回&models.User不只是models.User我不知道如何转换 interface{}*models.Usermodels.User

最佳答案

我认为这应该可行。您可以将其类型转换为 *User 并根据您的用例返回 User 值或 *User。

user = i.(*User)
return *user

关于go - 返回的接口(interface){}类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55645876/

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