首页 > 解决方案 > 扫描到其中一些是指针的结构字段

问题描述

我正在编写一个 GO 应用程序,并试图找到一种简单的方法来扫描数据库中的一行到结构字段。

我使用 pgx 连接到 postgresql 数据库

gqlgen 生成了这个类:

type Profile struct {
    Name      string          `json:"name"`
    JoinedAt  time.Time       `json:"joined_at"`
    Bio       *string         `json:"bio"`
}

然后我得到了从数据库获取用户配置文件的功能:

func GetUserProfile(ctx context.Context, profileDir string) (*model.Profile, error) {
    sqlQuery := `select name,joined_at::timestamptz,bio from foo where profile_dir=$1`
    var profile model.Profile
    if err := Connection.QueryRow(ctx, sqlQuery, profileDir).
        Scan(&profile.Name, &profile.JoinedAt, &profile.Bio); err != nil {
        return nil, err
    } else {
        return &profile, nil
    }
}

现在因为Bio是一个指针,我需要创建一个不是指针的变量,扫描它并将其地址分配给结构:

var profile model.Profile
var mybio string
...
Connection.QueryRow(...).Scan(...,&mybio)
profile.Bio=&mybio

有没有更简单的方法来扫描一行到可能有指针的结构?

标签: postgresqlgopointers

解决方案


如果Bio已经是一个指针,则不需要在 Scan 调用中使用额外的指针:

profile := Profile{
    Bio: new(string),
}

if err := Connection.QueryRow(ctx, sqlQuery, profileDir).
    Scan(&profile.Name, &profile.JoinedAt, profile.Bio); err != nil {
    return nil, err
} else {
    return &profile, nil
}

推荐阅读