From 91c4866d20086345f52b8d2f1df9087a0fc60568 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Wed, 17 Oct 2012 14:34:34 -0700 Subject: [PATCH] publish range --- examples.txt | 2 +- examples/range/range.go | 48 ++++++++++++++++++++++++++++++----------- examples/range/range.sh | 7 ++++++ 3 files changed, 43 insertions(+), 14 deletions(-) create mode 100644 examples/range/range.sh diff --git a/examples.txt b/examples.txt index 2252437..8a4cfb1 100644 --- a/examples.txt +++ b/examples.txt @@ -8,7 +8,7 @@ Switch Arrays Slices Maps -# Range +Range # Functions # Multiple Return Values # Varadic Functions diff --git a/examples/range/range.go b/examples/range/range.go index 56af522..a1fee6e 100644 --- a/examples/range/range.go +++ b/examples/range/range.go @@ -1,21 +1,43 @@ +// _range_ iterates over of elements in a variety of +// data structures. Let's see how to use `range` with some +// of the data structures we've already learned. + package main import "fmt" func main() { - var x [5]float64 - x[0] = 98 - x[1] = 93 - x[2] = 77 - x[3] = 82 - x[4] = 83 - var total float64 = 0 - for _, value := range x { - total += value + // Here we use `range` to sum the numbers in a slice. + // Arrays work like this too. + nums := []int{2, 3, 4} + sum := 0 + for _, num := range nums { + sum += num } - fmt.Println(total / float64(len(x))) -} + fmt.Println("sum:", sum) -// todo: comment on maps -// todo: comment on channels + // `range` on arrays and slices provides both the + // index and value for each entry. Above we didn't + // need the index, so we ignored it with the + // _blank identifier_ `_`. Sometimes we actually want + // the indexes though. + for i, num := range nums { + if num == 3 { + fmt.Println("index:", i) + } + } + + // `range` on map iterates over key/value pairs. + kvs := map[string]string{"a": "apple", "b": "bannana"} + for k, v := range kvs { + fmt.Printf("%s -> %s\n", k, v) + } + + // `range` on strings iterates over Unicode code + // points. The first value is the starting byte index + // of the `rune` and the second the `rune` itself. + for i, c := range "go" { + fmt.Println(i, c) + } +} diff --git a/examples/range/range.sh b/examples/range/range.sh new file mode 100644 index 0000000..7a61e75 --- /dev/null +++ b/examples/range/range.sh @@ -0,0 +1,7 @@ +$ go run range.go +sum: 9 +index: 1 +a -> apple +b -> bannana +0 103 +1 111