mercredi 14 octobre 2015

How to know if a variable of arbitrary type is Zero in Golang?

Because not all types are comparable, e.g. a slice. So we can't do this

var v ArbitraryType
v == reflect.Zero(reflect.TypeOf(v)).Interface()

Edit - Solution reflect.DeepEqual

var v ArbitratyType
zero := reflect.Zero(reflect.TypeOf(v)).Interface()
isZero := reflect.DeepEqual(v, zero)

Go documentation about reflect.DeepEqual

DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs.





Aucun commentaire:

Enregistrer un commentaire