reflect.Value.Set using unaddressable value

2019-05-01 02:48发布

g.GET("/", func(c echo.Context) error {
    var users []models.User
    err := db.Find(users).Error
    if err != nil {
        fmt.Println(err)
    }
    return c.JSON(http.StatusOK, users)
})

this is the code for getting and displaying users from table using slice is resulting following error from gorm

reflect.Value.Set using unaddressable value

标签: go go-gorm
3条回答
聊天终结者
2楼-- · 2019-05-01 03:30

You have to call Find with a pointer to the slice.

err := db.Find(&users).Error

relevant Gorm documentation: http://jinzhu.me/gorm/crud.html#query

查看更多
姐就是有狂的资本
3楼-- · 2019-05-01 03:34

Just to add clarification to S.Diego answers, changing this:

err := db.Find(users).Error

to this:

err := db.Find(&users).Error

the error says, the variable users is not addressable, because it is not a pointer.

查看更多
We Are One
4楼-- · 2019-05-01 03:41

In a very similar fashion to the accepted answer (but in a slightly different context), and an error that I keep making in different projects:

func migrate(db *gorm.DB) {
    db.AutoMigrate(User{}, Activity{})
}

becomes

func migrate(db *gorm.DB) {
    db.AutoMigrate(&User{}, &Activity{})
}

Notice the ampersands.

查看更多
登录 后发表回答