第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法將類型字符串用作 sql.NullString

無法將類型字符串用作 sql.NullString

Go
哆啦的時光機 2023-08-21 14:42:12
我正在創(chuàng)建一個gorm模型// Day is a corresponding day entrytype 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"`}我使用sql.NullString該字段,Something因為它可能為 NULL。因此,當我嘗試執(zhí)行一個典型gorm示例來驗證我的設置是否有效時:    db.Create(&Day{        Nameday:     "Monday",        Dateday:     "23-10-2019",        Something:   "a string goes here",        Holyday:      false,    })我得到:無法在字段值中使用“字符串位于此處”(類型字符串)作為 sql.NullString 類型Something如果字段可能為 NULL,我應該使用什么類型?
查看完整描述

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


查看完整回答
反對 回復 2023-08-21
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

package main


import (

    "github.com/guregu/null"

)


func main() {


    db.Create(&Day{

        Nameday: null.StringFrom("Monday"),

    })

}


查看完整回答
反對 回復 2023-08-21
  • 2 回答
  • 0 關注
  • 236 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號