Home > Backend Development > Golang > How to Initialize a sql.NullString Field in GORM?

How to Initialize a sql.NullString Field in GORM?

Susan Sarandon
Release: 2024-11-05 15:59:02
Original
908 people have browsed it

How to Initialize a sql.NullString Field in GORM?

Unable to Use Type String as SQL.NullString

Problem

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

Solution

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

Alternative

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template