publish range
This commit is contained in:
parent
ea6f0ec587
commit
91c4866d20
@ -8,7 +8,7 @@ Switch
|
|||||||
Arrays
|
Arrays
|
||||||
Slices
|
Slices
|
||||||
Maps
|
Maps
|
||||||
# Range
|
Range
|
||||||
# Functions
|
# Functions
|
||||||
# Multiple Return Values
|
# Multiple Return Values
|
||||||
# Varadic Functions
|
# Varadic Functions
|
||||||
|
@ -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
|
package main
|
||||||
|
|
||||||
import "fmt"
|
import "fmt"
|
||||||
|
|
||||||
func main() {
|
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
|
// Here we use `range` to sum the numbers in a slice.
|
||||||
for _, value := range x {
|
// Arrays work like this too.
|
||||||
total += value
|
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
|
// `range` on arrays and slices provides both the
|
||||||
// todo: comment on channels
|
// 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
7
examples/range/range.sh
Normal file
7
examples/range/range.sh
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
$ go run range.go
|
||||||
|
sum: 9
|
||||||
|
index: 1
|
||||||
|
a -> apple
|
||||||
|
b -> bannana
|
||||||
|
0 103
|
||||||
|
1 111
|
Loading…
x
Reference in New Issue
Block a user