foreach style for loops

Skip to first unread message

Mike Wiese

Nov 11, 2009, 4: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

Nov 11, 2009, 8:27:27 PM11/11/09
to Mike Wiese, golang-nuts
Mike Wiese <> 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".


Reply all
Reply to author
0 new messages