Go nulltype
Null friendly types
Nullable types friendly to json.Encoder, json.Decoder, database/sql, fmt.Stringer, text/template, html/template, some of ORMs. The project is written primarily in Go, first published in 2019. Key topics include: database, go, golang, json, null.
go-nulltype
Nullable types friendly to json.Encoder, json.Decoder, database/sql, fmt.Stringer, text/template, html/template, some of ORMs.
Supported types:
- NullBool
- NullString
- NullFloat64
- NullInt64
- NullTime
Usage
goimport "github.com/mattn/go-nulltype" type User struct { Name nulltype.NullString `json:"name"` }
friendly to Stringer
govar user User fmt.Println(user.Name.Valid()) // false fmt.Println(user.Name) // "" user.Name.Set("Bob") fmt.Println(user.Name.Valid()) // true fmt.Println(user.Name) // "Bob" fmt.Println(user.Name.StringValue() == "Bob") // true user.Name.Reset() fmt.Println(user.Name.Valid()) // false fmt.Println(user.Name) // ""
friendly to json.MarshalJSON
govar user User fmt.Println(user.Name.Valid()) // false json.NewEncoder(os.Stdout).Encode(user) // {"name": null} user.Name.Set("Bob") fmt.Println(user.Name.Valid()) // true json.NewEncoder(os.Stdout).Encode(user) // {"name": "Bob"}
friendly to json.UnmarshalJSON
govar user User s := `{"name": "Bob"}` json.NewDecoder(strings.NewReader(s)).Decode(&user) fmt.Println(user.Name.Valid()) // true fmt.Println(user.Name) // "Bob" s = `{"name": null}` json.NewDecoder(strings.NewReader(s)).Decode(&user) fmt.Println(user.Name.Valid()) // false fmt.Println(user.Name) // ""
friendly to database/sql
govar user User db.QueryRow(`SELECT name FROM users`).Scan(&user.Name) fmt.Println(user.Name.Valid()) // true or false fmt.Println(user.Name) // "Bob" or "" db.Exec(`INSERT INTO users(name) VALUES($1)`, user.Name)
friendly to ORM
Struct tag with gorp.
gotype Post struct { Id int64 `db:"post_id"` Created int64 Title string `db:",size:50"` Body nulltype.NullString `db:"body,size:1024"` }
gop := Post{ Created: time.Now().UnixNano(), Title: title, Body: nulltype.NullStringOf(body), } err = dbmap.Insert(&p)
Installation
go get github.com/mattn/go-nulltype
License
MIT
Author
Yasuhiro Matsumoto
Contributors
Showing top 5 contributors by commit count.
This article is auto-generated from mattn/go-nulltype via the GitHub API.Last fetched: 6/25/2026
