The sql.NullString https://golang.org/pkg/database/sql/#NullStringtype 实际上不是字符串类型,而是结构类型。它的定义为:
type NullString struct {
String string
Valid bool // Valid is true if String is not NULL
}
因此你需要这样初始化它:
db.Create(&Day{
Nameday: "Monday",
Dateday: "23-10-2019",
Something: sql.NullString{String: "a string goes here", Valid: true},
Holyday: false,
})
作为替代方案,如果您want为了在初始化可为空字符串时继续使用更简单的语法,您可以声明自己的可为空字符串类型,让它实现sql.Scanner
and driver.Valuer
接口,并利用空字节来发出信号NULL
value.
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
}
这样,如果您声明该字段Something
属于类型MyString
您可以按照最初的意图对其进行初始化。
db.Create(&Day{
Nameday: "Monday",
Dateday: "23-10-2019",
// here the string expression is an *untyped* string constant
// that will be implicitly converted to MyString because
// both `string` and `MyString` have the same *underlying* type.
Something: "a string goes here",
Holyday: false,
})
请记住,一旦您拥有类型的常量或变量,这仅适用于无类型常量string
,能够将其分配给MyString
您需要使用显式转换。
var s string
var ms MyString
s = "a string goes here"
ms = s // won't compile because s is not an untyped constant
ms = MyString(s) // you have to explicitly convert