Reputation: 8734
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,
}
}
Upvotes: 6
Views: 7114
Reputation: 9429
sql.NullString("[email protected]") << Does not work
Try:
sql.NullString{"[email protected]", true}
see http://golang.org/pkg/database/sql/#NullString
Upvotes: 7
Reputation: 646
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
Upvotes: 12