Unable to Use String as sql.NullString: Type Conversion Required
When creating a gorm model and using sql.NullString, an error may arise indicating the inability to use a string as an sql.NullString. This is because sql.NullString is a struct with specific requirements for initialization.
To resolve this issue, the Something field should be initialized using the correct syntax:
<code class="golang">db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", Something: sql.NullString{String: "a string goes here", Valid: true}, Holyday: false, })</code>
As an alternative, a custom nullable string type can be created to allow simpler syntax:
<code class="golang">type MyString string const MyStringNull MyString = "\x00" // Implement the necessary interfaces for GORM func (s MyString) Value() (driver.Value, error) { ... } func (s *MyString) Scan(src interface{}) error { ... }</code>
With this custom type, the Something field can be initialized as originally intended:
<code class="golang">db.Create(&Day{ Nameday: "Monday", Dateday: "23-10-2019", Something: "a string goes here", Holyday: false, })</code>
The above is the detailed content of How to Initialize sql.NullString in GORM Models?. For more information, please follow other related articles on the PHP Chinese website!