为了账号安全,请及时绑定邮箱和手机立即绑定

无法将类型字符串用作 sql.NullString

无法将类型字符串用作 sql.NullString

Go
哆啦的时光机 2023-08-21 14:42:12
我正在创建一个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。因此,当我尝试执行一个典型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,

})

作为替代方案,如果您想在初始化可为空字符串时继续使用更简单的语法,则可以声明自己的可为空字符串类型,让它实现 和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 *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 关注
  • 111 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信