How can I work with SQL NULL values and JSON in a good way?

前端 未结 2 1515
有刺的猬
有刺的猬 2020-12-05 02:21

Go types like Int64 and String cannot store null values, so I found I could use sql.NullInt64 and sql.NullString for this.

But when I use t

2条回答
  •  心在旅途
    2020-12-05 02:50

    If you use the null.v3 package, you won't need to implement any of the marshal or unmarshal methods. It's a superset of the sql.Null structs and is probably what you want.

    package main
    
    import "gopkg.in/guregu/null.v3"
    
    type Person struct {
        Name     string      `json:"id"`
        Age      int         `json:"age"`
        NickName null.String `json:"nickname"` // Optional
    }
    

    If you'd like to see a full Golang webserver that uses sqlite, nulls, and json you can consult this gist.

提交回复
热议问题