|
|
|
|
|
by jackielii
1481 days ago
|
|
I have an alternative solution to work with an existing struct that you can't change, e.g. protobuf generated code: https://jackieli.dev/posts/pointers-in-go-used-in-sql-scanne... type nullString struct {
s *string
}
func (ts nullString) Scan(value interface{}) error {
if value == nil {
*ts.s = "" // nil to empty
return nil
}
switch t := value.(type) {
case string:
*ts.s = t
default:
return fmt.Errorf("expect string in sql scan, got: %T", value)
}
return nil
}
func (n *nullString) Value() (driver.Value, error) {
if n.s == nil {
return "", nil
}
return *n.s, nil
}
Then use it: var node struct { Name string }
db.QueryRow("select name from node where id=?", id).Scan(nullString(&node.Name))
|
|