英文:
Golang declaring variables as NULLs
问题
根据下面的示例,我需要将email、firstname、dateofbirth等变量声明为NullStrings和NullTimes,因为我的User结构体正在使用它们。如何将变量声明为NULLs?
package entities
import (
"database/sql"
"github.com/go-sql-driver/mysql"
"testing"
"time"
)
var (
email = sql.NullString{"mail@gmail.com", true}
hashedPassword = "password"
firstName = "Lee"
lastName = "Brooks"
dateOfBirth = mysql.NullTime{Time: time.Now(), Valid: true}
height = 1.85
weight = 101.3
)
func privacyConcernedUser() *User {
return &User{
Email: email,
HashedPassword: hashedPassword,
FirstName: firstName,
LastName: lastName,
}
}
你可以使用sql.NullString
和mysql.NullTime
类型来声明变量为NULLs。在sql.NullString
中,你需要提供一个字符串和一个布尔值,表示该字符串是否为NULL。在mysql.NullTime
中,你需要提供一个时间值和一个布尔值,表示该时间是否为NULL。
英文:
As per the example below, I need to get email and firstname and dateofbirth and so on as NullStrings and NullTimes as required, as my User struct is using them. How do I declare variables as NULLs
package entities
import (
"database/sql"
"github.com/go-sql-driver/mysql"
"testing"
"time"
)
var (
email = sql.NullString("mail@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,
}
}
答案1
得分: 12
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)
}
你可以使用nsName.Valid
来检查NullString
是否有效。
http://golang.org/pkg/database/sql/#NullString
英文:
sql.NullString
isn't a drop-in replacement for the string
type, you have to some work with it.
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)
}
You can check if the NullString
is valid with nsName.Valid
.
答案2
得分: 7
sql.NullString("mail@gmail.com") << 不起作用
尝试:
sql.NullString{"mail@gmail.com", true}
参见 http://golang.org/pkg/database/sql/#NullString
英文:
sql.NullString("mail@gmail.com") << Does not work
Try:
sql.NullString{"mail@gmail.com", true}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论