如何使用go检查空字符串类型?

如何使用go检查空字符串类型?,go,Go,DB: 使用gorm从DB获取记录,然后 column: name value: NULL 出现错误: var name string if name != nil { // } 是的,nil用于go中的int类型,但在这种情况下,DB中的值为NULL,但不是,因此有必要检查NULL,怎么办?您应该注意sql类型: 只需在select语句中使用此类型的变量: invalid operation: name != nil (mismatched types string and nil)

DB:

使用gorm从DB获取记录,然后

column: name
value: NULL
出现错误:

var name string
if name != nil {
  //
}

是的,nil用于go中的int类型,但在这种情况下,DB中的值为NULL,但不是,因此有必要检查NULL,怎么办?

您应该注意sql类型:

只需在select语句中使用此类型的变量:

invalid operation: name != nil (mismatched types string and nil)
然后,您可以检查它是否有效,如果无效,您可以指定任何您想要的值:

var yourstr sql.NullString
db.Select("Select your string", &yourstr)
gorm中还有一个选择空字符串的函数:

if !yourstr.Valid{
  yourstr.String = ""
}

您还可以使用字符串指针映射数据库中的空值,但这会导致在不首先创建变量的情况下无法给出值的情况

yourstr := dbmap.SelectNullStr("Select your string")
或者您可以使用github.com/go-sql-driver/mysqlor或您正在使用的任何驱动程序和数据库/sql包实现。 如果要添加功能,可以基于这些类型定义自己的类型:

var name *string
if name != nil {
  //
}

// but
name = "will not work"
// NullInt64 is an alias for sql.NullInt64 data type
type NullInt64 sql.NullInt64
// NullBool is an alias for sql.NullBool data type
type NullBool sql.NullBool
// NullFloat64 is an alias for sql.NullFloat64 data type
type NullFloat64 sql.NullFloat64
// NullString is an alias for sql.NullString data type
type NullString sql.NullString
// NullTime is an alias for mysql.NullTime data type
type NullTime mysql.NullTime