go - *string 和 sql.NullString 之间的区别

标签 go

最近我一直在为 Golang 中的 SQL NULL 值而苦恼。在尝试使用 Decode()sql.NullString 解码 JSON 对象失败后,我在 StackOverflow 上找到了这个答案:

Assigning null to JSON fields instead of empty strings in Golang

使用字符串指针的解决方案似乎与 Decode() 和 nil 值完美配合。那么 sql.NullString*string 有什么区别呢? 它只是关于零检查吗?

最佳答案

SQL 与 Golang 有不同的空值。

如果您查看 sql.NullString 的定义,那么您会得到:

type NullString struct {
    String string
    Valid  bool // Valid is true if String is not NULL
}

如您所见,sql.NullString 是一种表示来自 SQL 的空字符串(对应于“NULL”)的方法。 另一方面,nil *string 是指向 nil 字符串的指针,因此两者不同。

关于go - *string 和 sql.NullString 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092155/

相关文章:

http - Go - 运行时错误 : invalid memory address or nil pointer dereference

email - 使用 Golang 通过 G Suite 发送电子邮件

sql - 是否可以使用 GoLang 数据库/sql 按名称检索列值

go - 命令 "go get github.com/gohugoio/hugo"失败并在期间以 2 退出

go - OSX 10.7.5 (Lion) 支持什么版本的 Go

go - 在 Raspberry Pi 上使用 GPIO 使用哪个包?

http - Golang 创建动态函数(在运行时)

c - Blowfish 结果在 OpenSSL 和 Golang 之间是不同的

database - 对可空结构字段使用 nil 或 Null* 哪个更好

go - 有没有办法覆盖包?