2 回答

TA貢獻1883條經驗 獲得超3個贊
該sql.NullString
類型實際上不是字符串類型,而是結構類型。它的定義為:
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,
})
作為替代方案,如果您想在初始化可為空字符串時繼續(xù)使用更簡單的語法,則可以聲明自己的可為空字符串類型,讓它實現 和sql.Scanner接口driver.Valuer,并利用空字節(jié)來表示值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 *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,
})
請記住,這僅適用于無類型常量,一旦您擁有 type 的常量或變量string,為了能夠將其分配給 a,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

TA貢獻1828條經驗 獲得超3個贊
package main
import (
"github.com/guregu/null"
)
func main() {
db.Create(&Day{
Nameday: null.StringFrom("Monday"),
})
}
- 2 回答
- 0 關注
- 236 瀏覽
添加回答
舉報