Curriculum Collections Iteration with range
Iteration with range
for i, v := range collection is the workhorse. Over a slice you get (index, value). Over a map you get (key, value). Over a string you get (byteIndex, rune). Over a channel you get just the value, with no index. Use _ to discard either side.
Exercises
11 ready
01
pick one
Translate the TS index-and-value loop to its idiomatic Go form.
02
pick one
Translate for (const n of nums) (value-only, no index) to Go.
03
pick one
Now flip exercise 2 around: you want ONLY the index, no value. Pick
04
pick one
Range over a map produces TWO values per iteration: the key and
05
pick one
Range over a MAP one-value-form: which one does Go emit, key or
06
pick one
Go 1.22 added a new range form that lets you iterate over an
07
fill blanks
Sum a slice of ints — the productive use of for _, v := range.
08
fill blanks
Iterate over a map and print every key→value pair. Fill in the
09
type one line
Ranging over a STRING in Go gives you the BYTE INDEX and the
10
type one line
Classic loop-variable closure puzzle. Build a slice of functions
11
write a program
Capstone: write a reverse(s string) string function that