简体   繁体   中英

Golang declaring variables as NULLs

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,
    }
}

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 .

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

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

Try:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM