After using db.Query
and rows.Scan
to populate a sql.NullString
with a NULL
value such that its .Valid
field is false
, is it guaranteed that its .String
will hold the empty string ""
?
I ask because it would be snazzy if I could use this:
res := ns.String
Instead of this:
var res string
if ns.Valid {
res = ns.String
}
In the current implementation yes, but the docs explicitly say to check Valid before using String. Ignore the docs at your own risk.
If you want to be safe, simply copy the type into your own package; then you know it's not going to change with the next Go release.
If you don't do that, I strongly suggest to write a test:
func TestEmptyNullString(t *testing.T) {
var x sql.NullString
x.String = "foo"
x.Scan(nil)
if x.String != "" {
t.Error("string not empty after Scan")
}
}