我正在編寫一個 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.Profilevar mybio string...Connection.QueryRow(...).Scan(...,&mybio)profile.Bio=&mybio有沒有更簡單的方法來掃描一行到可能有指針的結構?
1 回答

侃侃無極
TA貢獻2051條經驗 獲得超10個贊
如果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
}
- 1 回答
- 0 關注
- 80 瀏覽
添加回答
舉報
0/150
提交
取消