2014-01-17 61 views
4

根據以下示例,我需要根據需要將NullStrings和NullTimes作爲電子郵件和名字以及dateofbirth等,因爲我的User結構正在使用它們。如何變量聲明爲空* SGolang聲明變量爲空* s

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

回答

9

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

您可以檢查NullStringnsName.Valid有效。

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