from what i understand when i write a method on a pointer receiver i can modify the values, lets say i have this structure
type User Struct {
ID uint64
Name string
Avatar *string
// other fields
}
func (user *User) Update() error {
sql := `UPDATE users SET "avatar" = $1 RETURNING *`
err := models.DB.QueryRow(sql, user.Avatar).Scan(
user.ID, // &user.ID works
user.Name, // &user.Name works
user.Avatar, // &user.Avatar works
)
return err
}
so technically if user
is a pointer to a structure this code should work? but when i call the Update
method i get receiver is not a pointer
error, what am i missing?
Though user
is a pointer in your method, you're not passing user
to Scan
, you're passing the field values. When you write
user.ID
It's equivalent to
(*user).ID // this copies the ID value
(see the relevant section of Selectors in the spec)
In order to get the address of the ID field, you need to use the &
operator
&user.ID // takes the address of ID