Home > Article > Backend Development > How to Handle Nullable String Fields with GORM and sql.NullString?
In GORM, using sql.NullString for a field that may be NULL faces the error:
cannot use "a string goes here", (type string) as type sql.NullString in field value
while trying to execute a simple GORM validation example.
sql.NullString is not a string type but a struct type defined as:
type NullString struct { String string Valid bool // Valid is true if String is not NULL }
To initialize it correctly, use the following syntax:
db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", Something: sql.NullString{String: "a string goes here", Valid: true}, Holyday: false, })
Alternatively, to retain the simpler initialization syntax:
Define a custom nullable string type:
type MyString string
Override the methods Value() and Scan() as follows:
func (s MyString) Value() (driver.Value, error) { if s == MyStringNull { return nil, nil } return []byte(s), nil } func (s *MyString) Scan(src interface{}) error { switch v := src.(type) { case string: *s = MyString(v) case []byte: *s = MyString(v) case nil: *s = MyStringNull } return nil }
Declare the Something field as MyString and initialize it as intended:
db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", // Here, an untyped string constant will explicitly convert to MyString because they have the same underlying type. Something: "a string goes here", Holyday: false, })
The above is the detailed content of How to Handle Nullable String Fields with GORM and sql.NullString?. For more information, please follow other related articles on the PHP Chinese website!