40
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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Krishna Satya
  • 775
  • 2
  • 9
  • 21
  • 2
    This is more generic thatn `go-gorm`. `go-yaml`'s `Unmarshal` suffers the same issue when you pass it something that's not properly ampersanded. (Not the technical term, but it is what it is) – meh May 29 '19 at 22:26

3 Answers3

71

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

S. Diego
  • 876
  • 6
  • 6
24

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.

Felipe Valdes
  • 1,998
  • 15
  • 26
9

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.

Rambatino
  • 4,716
  • 1
  • 33
  • 56