reflect.Value.Set使用不可寻址的值

huangapple go评论139阅读模式
英文:

reflect.Value.Set using unaddressable value

问题

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)
})

这是从数据库表中获取并显示用户的代码,使用切片(slice)。使用gorm时出现以下错误:

reflect.Value.Set使用不可寻址的值

英文:
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

答案1

得分: 71

你必须使用指向切片的指针来调用Find函数。

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

相关的Gorm文档:http://jinzhu.me/gorm/crud.html#query

英文:

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

答案2

得分: 24

只是为了澄清S.Diego的回答,将这个代码片段中的部分进行更改:

err := db.Find(users).Error

改为:

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

错误提示说,变量users不可寻址,因为它不是一个指针。

英文:

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.

答案3

得分: 9

以非常相似的方式(但在稍微不同的上下文中),我一直在不同的项目中犯同样的错误:

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

变成了:

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

注意到了这些和号(ampersands)。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月22日 13:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45809746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定