range expression

232 views
Skip to first unread message

Martin Hurton

unread,
Apr 17, 2011, 3:09:31 PM4/17/11
to golang-nuts
Hi,

The length of nil slice, map, and channel are 0.
What's the expected behaviour of loop when the range expression
evaluates to nil?

- Martin

Steven

unread,
Apr 17, 2011, 3:58:29 PM4/17/11
to Martin Hurton, golang-nuts
From the specification:
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.

A nil slice, map, or channel have length zero, meaning they have no entries to iterate over. Therefore, the expected behaviour is that there will be zero iterations, since iteration occurs "for each entry". 

Rob 'Commander' Pike

unread,
Apr 17, 2011, 4:00:24 PM4/17/11
to Martin Hurton, golang-nuts
I'm not certain this is well specified. That should be addressed.

They'll all execute zero times, except for the channel case, which
will panic ("range over a nil channel"). Outside of s special case in
select, with specific purpose, nil channels are never helpful,
although you can ask their length. This should be clarified in the
spec, one way or the other.

-rob

Brad Fitzpatrick

unread,
Apr 17, 2011, 6:15:26 PM4/17/11
to Rob 'Commander' Pike, Martin Hurton, golang-nuts
Reply all
Reply to author
Forward
0 new messages