for loop
with range keyword used to iterate over the elements of string, array, map and
slice.
Iterate over an array
byteArray
:= []byte{97, 98, 99, 100, 101, 102, 103}
for index,
value := range byteArray {
fmt.Println(index, ":",
value)
}
Iterate over a map
employees
:= map[int]string{}
employees[0]
= "Krishna"
employees[1]
= "Chamu"
employees[2]
= "Ram"
for key,
value := range employees {
fmt.Println(key, " : ",
value)
}
package main import ( "fmt" ) func main() { byteArray := []byte{97, 98, 99, 100, 101, 102, 103} fmt.Println("Elements of byte array") for index, value := range byteArray { fmt.Println(index, ":", value) } employees := map[int]string{} employees[0] = "Krishna" employees[1] = "Chamu" employees[2] = "Ram" fmt.Println("\nValues in map are") for key, value := range employees { fmt.Println(key, " : ", value) } }
Output
Elements
of byte array
0 : 97
1 : 98
2 : 99
3 : 100
4 : 101
5 : 102
6 : 103
Values in
map are
0 :
Krishna
1 : Chamu
2 : Ram
No comments:
Post a Comment