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

如何在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 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?