When creating a GORM model with a field of type sql.NullString, an attempt to initialize the field with a string value results in the error:
cannot use "a string goes here", (type string) as type sql.NullString in field value
The sql.NullString type is not actually a string type but a struct that encapsulates a string and a boolean flag indicating whether the string is valid (not NULL). To initialize a sql.NullString field, it must be initialized with a struct value, not a string value.
The following code demonstrates how to correctly initialize a sql.NullString field:
<code class="go">db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", Something: sql.NullString{String: "a string goes here", Valid: true}, Holyday: false, })</code>
Alternatively, a custom nullable string type can be defined that implements the sql.Scanner and driver.Valuer interfaces and uses a null byte to signal a NULL value. With this custom type, the original syntax can be used to initialize a nullable string field.
Custom Type:
<code class="go">type MyString string const MyStringNull MyString = "\x00" // implements driver.Valuer, will be invoked automatically when written to the db func (s MyString) Value() (driver.Value, error) { if s == MyStringNull { return nil, nil } return []byte(s), nil } // implements sql.Scanner, will be invoked automatically when read from the db 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 }</code>
Usage:
<code class="go">db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", // no need for explicit typing/conversion Something: "a string goes here", Holyday: false, })</code>
The above is the detailed content of How to Initialize a sql.NullString Field in GORM?. For more information, please follow other related articles on the PHP Chinese website!