dsm17496 2019-03-13 19:43 采纳率: 100%
浏览 1288
已采纳

如何在Golang中的空字符串字段中返回空值?

我有这样的 struct 在Golang应用程序:

type Employee struct {
    ID int `json:"employee_id"`
    Email *string `json:"employee_email"`
    LastName *string `json:"employee_last_name"`
    FirstName *string `json:"employee_first_name"`
    Sex *string `json:"employee_sex"`
}

此结构的某些字符串字段可以为空。 如果我用 *string应用程序返回我"". 如果使用 sql.NullString 它就会返回给我这样的结果:

"employee_last_name": {
    String: "",
    Valid: true
}

我想显示的是字符串字段为空。 null

在文档中我找到了这样的代码:

type NullString struct {
    String string
    Valid  bool
}

func (ns *NullString) Scan(value interface{}) error {
    if value == nil {
        ns.String, ns.Valid = "", false
        return nil
    }
    ns.Valid = true
    return convertAssign(&ns.String, value)
}

func (ns NullString) Value() (driver.Value, error) {
    if !ns.Valid {
        return nil, nil
    }
    return ns.String, nil
}

据我了解,这段代码可以帮助我解决问题,对吗? 我需要在应用程序中导入什么才能使用 convertAssign这个功能呢?

  • 写回答

2条回答 默认 最新

  • duan5801 2019-03-13 20:07
    关注

    Edit:

    What you want to do is not possible according to the oracle go driver docs:

    sql.NullString

    sql.NullString is not supported: Oracle DB does not differentiate between an empty string ("") and a NULL

    Original Answer:

    Need more details on the SQL database type you are connecting to. I know the go SQLite3 pkg - github.com/mattn/go-sqlite3 - supports setting nil for values of type *string.

    Check the details of the driver you are using to connect to the database. For instance with MySQL, getting SQL date fields into go's native time.Time struct type is not set by default - it must be turned on at the driver level.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵