将指针作为接口类型传递

时间:2018-11-14 00:18:01

标签: go

帮帮我。我被困在这里,我做了一个checkRecordExistence来检查记录是否存在。此函数将模型作为接口类型,我将模型传递给First函数,该函数也将模型作为接口类型,但它没有工作

    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函数时,它崩溃了

        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(query,field ...)。First(model),但我找不到任何解决方案,谢谢任何人的帮助。

>

1 个答案:

答案 0 :(得分:3)

根据https://github.com/jinzhu/gorm/issues/394,参数model应该是一个指针。我认为下面的代码可以工作。

if exist := checkRecordExistence(&user, "username = ?", username); !exist {
    return
}