我正在创建一个gorm模型
// Day is a corresponding day entry
type Day struct {
gorm.Model
Dateday string `json:"dateday" gorm:"type:date;NOT NULL"`
Nameday string `json:"nameday" gorm:"type:varchar(100);NOT NULL"`
Something sql.NullString `json:"salad"`
Holyday bool `json:"holyday"`
}
Run Code Online (Sandbox Code Playgroud)
我正在使用sql.NullString该字段,Something因为它可能为 NULL。
因此,当我尝试执行一个典型gorm示例来验证我的设置是否有效时:
db.Create(&Day{
Nameday: "Monday",
Dateday: "23-10-2019",
Something: "a string goes here",
Holyday: false,
})
Run Code Online (Sandbox Code Playgroud)
我得到:
不能使用“一个字符串在这里”,(字符串类型)作为字段值中的类型 sql.NullString
如果Something字段可能为 NULL,我应该为该字段使用什么类型?
mko*_*iva 11
该sql.NullString类型实际上不是字符串类型,而是结构类型。它被定义为:
type NullString struct {
String string
Valid bool // Valid is true if String is not NULL
}
Run Code Online (Sandbox Code Playgroud)
因此,您需要将其初始化为:
db.Create(&Day{
Nameday: "Monday",
Dateday: "23-10-2019",
Something: sql.NullString{String: "a string goes here", Valid: true},
Holyday: false,
})
Run Code Online (Sandbox Code Playgroud)
作为替代方案,如果您想在初始化可空字符串时继续使用更简单的语法,您可以声明自己的可空字符串类型,让它实现sql.Scanner和driver.Valuer接口,并利用空字节来表示NULL值。
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 *String) Scan(src interface{}) error {
switch v := src.(type) {
case string:
*s = String(v)
case []byte:
*s = String(v)
case nil:
*s = StringNull
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
有了这个,如果您将字段声明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,
})
Run Code Online (Sandbox Code Playgroud)
请记住,这仅适用于无类型常量,一旦您有一个常量或 type 变量string,就能够将其分配给 aMyString您需要使用显式转换。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6951 次 |
| 最近记录: |