dongpi9480 2019-04-17 10:38
浏览 87
已采纳

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

DB:

column: name
value: NULL

Get the record from DB with gorm, then

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

Got error:

invalid operation: name != nil (mismatched types string and nil)

Yes, nil is using for int type in go, but this case, the value in DB is NULL but not "", so it's necessary to check null, how to do?

  • 写回答

2条回答 默认 最新

  • dpa89292 2019-04-17 13:52
    关注

    You can also use a pointer to string to map NULL values from the database, but this will create cases where you cannot give values without creating a variable first.

    var name *string
    if name != nil {
      //
    }
    
    // but
    name = "will not work"
    

    Or you could use the github.com/go-sql-driver/mysql(or whatever driver you are using) and database/sql package implementations. You can define your own types based on those if you want to add functionality:

    // 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大