How to use range iterates in Go

6 Answers

0 votes
package main
  
import (
    "fmt"
)
  
func main() {
	arr := []int{5, 1, 9, 7}
    sum := 0
	
    for _, n := range arr {
        sum += n
    }
	
    fmt.Println(sum)
}
  
  
  
/*
run:
  
22

*/

 



answered Feb 22, 2020 by avibootz
0 votes
package main
  
import (
    "fmt"
)
  
func main() {
	arr := []int{5, 1, 9, 2, 7}
	
    for i, n := range arr {
        if n > 5 {
            fmt.Println(i)
        }
    }
}	
  
  
  
/*
run:
  
2
4

*/

 



answered Feb 22, 2020 by avibootz
0 votes
package main
   
import (
    "fmt"
)
   
func main() {
    m := map[string]string{"a": "go", "b": "nodejs", "c": "python"}
	
    for key, val := range m {
        fmt.Printf("%s : %s\n", key, val)
    }
}   
   
   
   
/*
run:
   
a : go
b : nodejs
c : python
 
*/

 



answered Feb 22, 2020 by avibootz
edited Feb 29, 2020 by avibootz
0 votes
package main
  
import (
    "fmt"
)
  
func main() {
	m := map[int]string{1: "go", 2: "nodejs", 3: "python", 4: "php"}
	
    for key, val := range m {
        fmt.Printf("%d : %s\n", key, val)
    }
}	
  
  
  
/*
run:
  
1 : go
2 : nodejs
3 : python
4 : php

*/

 



answered Feb 22, 2020 by avibootz
edited Feb 29, 2020 by avibootz
0 votes
package main
    
import (
    "fmt"
)
    
func main() {
    m := map[string]string{"a": "go", "b": "nodejs", "c": "python"}
     
   for key := range m {
        fmt.Println(key)
    }
}   
    
    
    
/*
run:
    
a
b
c
 
*/

 



answered Feb 22, 2020 by avibootz
edited Feb 29, 2020 by avibootz
0 votes
package main
   
import (
    "fmt"
)
   
func main() {
	for i, ch := range "golang" {
        fmt.Println(i, ch, string(ch))
    }
}   
   
   
   
/*
run:
   
0 103 g
1 111 o
2 108 l
3 97 a
4 110 n
5 103 g

*/

 



answered Feb 22, 2020 by avibootz
...