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

如何在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条)

报告相同问题?

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化