Does range over a nil slice have defined behavior?

16,167 views
Skip to first unread message

Brad Fitzpatrick

unread,
Feb 4, 2011, 5:17:48 PM2/4/11
to golang-nuts
Should range over a nil slice have defined behavior?

I don't see it in the spec:  (unless I missed it)


I would guess it might be safe, as the length of a nil slice is defined to be zero.

Worth calling out explicitly?

Steven

unread,
Feb 4, 2011, 5:50:03 PM2/4/11
to Brad Fitzpatrick, golang-nuts
I'd say that:
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel.
and
The length and capacity of a nil slice, map, or channel are 0.

mean that a nil slice has 0 entries, and therefore the range clause will produce no iterations. Since the spec doesn't distinguish between nil and non-nil in the range clause, and it does specify the number of elements of a nil slice, an implementation that failed when ranging over a nil slice would be in violation of the spec.
Reply all
Reply to author
Forward
0 new messages