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,
}
}
The variable type gets inferred by the Go compiler after the declaration happens so it cannot be reassigned with a new type. Multiple variables can be declared using the shorthand syntax of variable declaration.
How do you express a "null" value in Go? The equivalent of NULL is nil, as you already discovered. Note, though, that you don't generally need to initialize things to nil or zero in Go, because by default all variables (including dynamically allocated ones) are set to “zero values” according to type (numbers zero, references nil ).
Short Variable Declaration Operator (:=) in Go Last Updated : 17 May, 2021 Short Variable Declaration Operator (:=) in Golang is used to create the variables having a proper name and initial value. The main purpose of using this operator to declare and initialize the local variables inside the functions and to narrowing the scope of the variables.
The blank identifier is the single underscore (_) operator. It is used to ignore the values returned by functions or import for side-effects. Why is it needed? Go compiler throws an error whenever it encounters a variable declared but not used. Now we can simply use the blank identifier and not declare any variable at all.
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("[email protected]") << Does not work
Try:
sql.NullString{"[email protected]", true}
see http://golang.org/pkg/database/sql/#NullString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With