根据下面的示例,我需要根据需要获取电子邮件和名字以及dateofbirth等NullStrings和NullTimes,因为我的User结构正在使用它们。如何将变量声明为NULL
package entities
import (
"database/sql"
"github.com/go-sql-driver/mysql"
"testing"
"time"
)
var (
email = sql.NullString("leebrooks0@gmail.com") << Does not work
hashedPassword = "password"
firstName = "Lee"
lastName = "Brooks"
dateOfBirth = time.Now
height = 1.85
weight = 101.3
)
func privacyConcernedUser() *User {
return &User{
Email: email, << These all complain eg: cannot use Email (type string) as type sql.NullString in field value
HashedPassword: hashedPassword,
FirstName: firstName,
LastName: lastName,
}
}
答案 0 :(得分:10)
sql.NullString
不是string
类型的替代品,您必须使用它。
package main
import "database/sql"
import "fmt"
type User struct {
Name string
}
func main() {
var nsName sql.NullString
if err := nsName.Scan("User's Name"); err != nil {
panic(err)
}
user := &User{Name: nsName.String}
fmt.Println(user)
}
您可以使用NullString
检查nsName.Valid
是否有效。
答案 1 :(得分:4)
sql.NullString("leebrooks0@gmail.com") << Does not work
尝试:
sql.NullString{"leebrooks0@gmail.com", true}