The for range construct is useful in many context. It can be used to traverse every item in a collection. It is similar to foreach in other languages. But, we still have the index at each iteration in for range construct.
Syntax:
- for ix, val := range coll { }
Go For Range Example
- import "fmt"
- func main() {
- nums := []int{2, 3, 4}
- sum := 0
- for _, value := range nums {
- sum += value
- }
- fmt.Println("sum:", sum)
- for i, num := range nums {
- if num == 3 {
- fmt.Println("index:", I)
- }
- }
- kvs := map[string]string{"1":"mango","2":"apple","3":"banana"}
- for k, v := range kvs {
- fmt.Printf("%s -> %s\n", k, v)
- }
- for k := range kvs {
- fmt.Println("key:", k)
- }
- for i, c := range "Hi" {
- fmt.Println(i, c)
- }
- }
Output:
sum: 60
1 -> mango
2 -> apple
3 -> banana
key: 1
key: 2
key: 3
0 72
1 105
No comments:
Post a Comment