6

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("[email protected]") << 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 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

Comments

7

sql.NullString("[email protected]") << Does not work

Try:

sql.NullString{"[email protected]", true}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.