null
is a package for providing types to handle nullable values.
For a comparable
type V
, the nullable type null.T[V]
implements sql.Scanner
and json.Unmarshaler
. It can be used with types such as:
- Named integer types like
time.Duration
- Structs with
comparable
fields - Arrays consisting of
comparable
elements
null.T
is oriented towards immutability. Therefore, unlike sql.NullInt64
, null.T
does not have APIs for modification.
null.T
does not expose its fields.null.T
does not have methods for modification (excludingScan
andUnmarshal
).
func main() {
var d null.T[time.Duration]
// "null" -> null
json.Unmarshal([]byte(`null`), &d)
fmt.Printf("valid: %v, value: %v\n", !d.IsNull(), d.ValueOrZero())
// Output:
// valid: false, value: 0s
// "0" -> "0s" (zero value, not null)
json.Unmarshal([]byte(`0`), &d)
fmt.Printf("valid: %v, value: %v\n", !d.IsNull(), d.ValueOrZero())
// Output:
// valid: true, value: 0s
// nil -> null
d.Scan(nil)
fmt.Printf("valid: %v, value: %v\n", !d.IsNull(), d.ValueOrZero())
// Output:
// valid: false, value: 0s
}
Differences from gopkg.in/guregu/null
Differences from the well-known package gopkg.in/guregu/null, which also defines nullable types include:
- Generics:
null
supports not onlybool
,int64
,float64
,string
, andtime.Time
, but also anycomparable
type. - Immutablity:
null.T
does not have APIs for modification.null.T
does not expose its fields.null.T
does not have aSetValid
method.
- Fewer APIs: This package does not provide several APIs defined in guregu/null.
New*
MarshalText
,UnmarshalText
SetValid
guregu/null.Int
can json-unmarshal quoted numbers like"123"
, butnull.T[int64]
cannot. This aligns with the behavior whenjson.Unmarshal
is applied toint64
.guregu/null.Float
can json-unmarshal quoted numbers like"1.23"
, butnull.T[float64]
cannot. This aligns with the behavior whenjson.Unmarshal
is applied tofloat64
.- For floats with extremely small or large absolute values, the output of
MarshalJSON
forguregu/null.Float
andnull.T[float64]
is different.null.T[float64]
matches the behavior whenfloat64
is passed tojson.MarshalJSON
. - The method
IsZero
has been renamed toIsNull
.