Home >Backend Development >Golang >How to Handle Nullable String Fields with GORM and sql.NullString?

How to Handle Nullable String Fields with GORM and sql.NullString?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 03:29:02709browse

How to Handle Nullable String Fields with GORM and sql.NullString?

Unable to Use Type String as sql.NullString

Query

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.

Resolution

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,
})

Alternative Solution

Alternatively, to retain the simpler initialization syntax:

  1. Define a custom nullable string type:

    type MyString string
  2. Implement the sql.Scanner and driver.Valuer interfaces to handle value conversion.
  3. 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
    }
  4. 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!

Statement:
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