我有这样的 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
这个功能呢?
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.
In the Go language specification nil
is not a valid value for type string
. the default, zero value is ""
.