Saturday 28 August 2021

Go for range construct

 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:

  1. for ix, val := range coll { }  

Go For Range Example

  1. import "fmt"  
  2. func main() {  
  3.    nums := []int{234}  
  4.    sum := 0  
  5.    for _, value := range nums {// "_ " is to ignore the index  
  6.       sum += value  
  7.    }  
  8.    fmt.Println("sum:", sum)  
  9.    for i, num := range nums {  
  10.       if num == 3 {  
  11.          fmt.Println("index:", I)  
  12.       }  
  13.    }  
  14.    kvs := map[string]string{"1":"mango","2":"apple","3":"banana"}  
  15.    for k, v := range kvs {  
  16.       fmt.Printf("%s -> %s\n", k, v)  
  17.    }      
  18.    for k := range kvs {  
  19.       fmt.Println("key:", k)  
  20.    }  
  21.    for i, c := range "Hi" {  
  22.       fmt.Println(i, c)  
  23.    }  
  24. }  

Output:

sum: 60
1 -> mango
2 -> apple
3 -> banana
key: 1
key: 2
key: 3
0 72
1 105

No comments:

Post a Comment