Golang将变量声明为NULL

时间:2014-01-17 01:49:21

标签: go

根据下面的示例,我需要根据需要获取电子邮件和名字以及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,
    }
}

2 个答案:

答案 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是否有效。

http://golang.org/pkg/database/sql/#NullString

答案 1 :(得分:4)

sql.NullString("leebrooks0@gmail.com") << Does not work

尝试:

sql.NullString{"leebrooks0@gmail.com", true}

请参阅http://golang.org/pkg/database/sql/#NullString