Hacker News new | past | comments | ask | show | jobs | submit login

This is the most satisfying answer, but it doesn't make the implications less complex.



What implications did you have in mind?

In languages with null and type inference, `var x = null` is probably not going to infer the type you want. In languages with function overloading (which is essentially the case for Go `len`), `f(null)` is going to be a compile-time error if multiple overloads are potentially null.


the ability to cast nil as a zero length array means there's no difference between a function that returns a zero length array and a function that returns nil (assuming some casting process takes place). It could be a subtle and annoying bug to track down the difference.


nil isn't cast to an empty slice (Go doesn't have casts, except maybe the new pointer-to-array syntax if you want to count that), nil is the default value of a slice, and that value is also empty. Other empty slices may be non-nil, because they may have capacity, or have been sliced out of another buffer, etc.

Of the various legitimate issues around nil (box vs. unboxed, nil receivers, nilability of all pointers), this is the most not-actually-ever-an-issue.


Oddly the first issue I came across today was folks being confused about this. I haven't gotten to the bottom of where the code is now, but this go library was messing up len == 0 vs nility and someone forked it to fix it: https://github.com/algorithmiaio/mapstructure/pull/1 It may not be a common bug but that doesn't make it less of a pitfall.


No, this is a terrible idea and you're in for a world of pain. If you want to distinguish "not set" from "length zero" use a *[]T or ([]T, bool), not a nil vs. non-nil-empty []T. A nil slice is not any special kind of empty slice, it is just the most efficient representation of an empty slice.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

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

Search: