foreach style for loops

1,871 views
Skip to first unread message

Mike Wiese

unread,
Nov 11, 2009, 9:50:44 AM11/11/09
to golang-nuts
I think range clauses deserve mention in the tutorial! I was very
happy when I got to this point in the Language 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 first assigns the current index or key to an
iteration variable - or the current (index, element) or (key, value)
pair to a pair of iteration variables - and then executes the block.

var a [10]string;
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":
5, "sun":6};

for i, s := range a {
// type of i is int
// type of s is string
// s == a[i]
g(i, s)
}

var key string;
var val interface {}; // value type of m is assignment compatible
with val
for key, val = range m {
h(key, val)
}
// key == last map key encountered in iteration
// val == map[key]

Ian Lance Taylor

unread,
Nov 12, 2009, 1:27:27 AM11/12/09
to Mike Wiese, golang-nuts
Mike Wiese <mike....@gmail.com> writes:

> I think range clauses deserve mention in the tutorial!

It's hard to know how long to make certain documents. Range clauses
are covered in "Effective Go".

Ian

Reply all
Reply to author
Forward
0 new messages