dsm17496
dsm17496
采纳率100%
2019-03-13 19:43 阅读 808
已采纳

如何在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 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.

    点赞 评论 复制链接分享
  • duanqi5114 duanqi5114 2019-03-13 19:50

    In the Go language specification nil is not a valid value for type string. the default, zero value is "".

    The top answer for this question goes into more detail.

    点赞 评论 复制链接分享

相关推荐