How to Initialize sql.NullString in GORM Models?

DDD
Release: 2024-11-05 12:46:02
Original
745 people have browsed it

How to Initialize sql.NullString in GORM Models?

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template