英文:
how to scan a database row into a pointer to a structure?
问题
根据我理解,当我在指针接收器上编写一个方法时,我可以修改值。假设我有以下结构体:
type User struct {
ID uint64
Name string
Avatar *string
// 其他字段
}
func (user *User) Update() error {
sql := `UPDATE users SET "avatar" = $1 RETURNING *`
err := models.DB.QueryRow(sql, user.Avatar).Scan(
&user.ID,
&user.Name,
&user.Avatar,
)
return err
}
从技术上讲,如果user
是一个指向结构体的指针,这段代码应该可以工作。但是,当我调用Update
方法时,我收到了"receiver is not a pointer"的错误消息。我漏掉了什么?
英文:
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?
答案1
得分: 2
尽管在你的方法中user
是一个指针,但你没有将user
传递给Scan
,而是传递了字段的值。当你写下
user.ID
它等同于
(*user).ID // 这会复制ID的值
(请参阅规范中的Selectors相关部分)
为了获得ID字段的地址,你需要使用&
运算符
&user.ID // 取ID的地址
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论