首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >以接口类型传递指针

以接口类型传递指针
EN

Stack Overflow用户
提问于 2018-11-14 00:18:01
回答 1查看 241关注 0票数 1

帮帮我。我被困在这里,我做了一个checkRecordExistence来检查是否存在一个record.This函数,把一个模型作为一个接口类型,我把模型传递给第一个函数,它也把模型作为一个接口类型,但是它不能工作。

代码语言:javascript
复制
    func checkRecordExistence(model interface{}, query string, field ...interface{}) bool {
        if err := db.GetDB().Where(query, field...).First(model).Error; gorm.IsRecordNotFoundError(err) {
            return false
        }
        return true
    }

    // GetPlaylists of a specific user
    func GetPlaylists(username string) (playlists []Playlist) {
        playlists = []Playlist{}
        user := User{}
        if exist := checkRecordExistence(user, "username = ?", username); !exist {
            return
        }
        db.GetDB().Preload("Songs.Artists").Preload("Songs").Model(&user).Related(&playlists, "UserRefer")
        return
    }

当我调用GetPlaylists函数时,它崩溃了

代码语言:javascript
复制
        eflect.Value.Addr of unaddressable value
    /usr/lib/go/src/runtime/panic.go:513 (0x42c4d8)
            gopanic: reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz))
    /usr/lib/go/src/reflect/value.go:245 (0x4ae0c5)
            Value.Addr: panic("reflect.Value.Addr of unaddressable value")
    /home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/callback_query.go:74 (0x54f1b4)
            queryCallback: scope.scan(rows, columns, scope.New(elem.Addr().Interface()).Fields())
    /home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/scope.go:857 (0x5767a4)
            (*Scope).callCallbacks: (*f)(scope)
    /home/anhthi/go/src/github.com/anhthii/go-echo/vendor/github.com/jinzhu/gorm/main.go:289 (0x56528e)
            (*DB).First: inlineCondition(where...).callCallbacks(s.parent.callbacks.queries).db
    /home/anhthi/go/src/github.com/anhthii/go-echo/db/models/playlist.go:35 (0x676c06)
            checkRecordExistence: if err := db.GetDB().Where(query, field...).First(model).Error; gorm.IsRecordNotFoundError(err) {
    /home/anhthi/go/src/github.com/anhthii/go-echo/db/models/playlist.go:45 (0x676dfc)
            GetPlaylists: if exist := checkRecordExistence(user, "username = ?", username); !exist {

我认为问题就在这里:.Where(查询,字段.).First(模型),但是我找不到任何解决方案,如果有人能帮我的话,谢谢。

EN

回答 1

Stack Overflow用户

发布于 2018-11-14 00:40:51

根据https://github.com/jinzhu/gorm/issues/394,参数model应该是指针。我想下面的代码会有效的。

代码语言:javascript
复制
if exist := checkRecordExistence(&user, "username = ?", username); !exist {
    return
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53291368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档