如何将数据库行扫描到指向结构体的指针中?

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

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

huangapple
  • 本文由 发表于 2016年1月15日 02:14:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/34796812.html
匿名

发表评论

匿名网友

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

确定