Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> the len of an empty slice is 0, but the slice itself is == to nil

That’s not true. An empty slice is initialized: []T{} or make(T[]); it’s not equal to nil.[1] The zero value nil slice is technically not an “empty slice”. Colloquially you may call a nil slice an empty slice, but the nil-ness is still an important distinction that manifests in e.g. encoding/json.Marshal; nil marshals to null, whereas an initialized empty slice marshals to [].

If you want to test the emptiness of a slice, test the length, don’t compare it to nil.

[1] https://go.dev/play/p/IP2NIgwvaTR?v=gotip



How does it look with json.Unmarshal? Does a JSON null decode into nil or an empty slice? And a missing JSON field?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: