Thursday, 2 May 2019

Go language: Iterate over a slice using range keyword


Example 1: Get the value of slice from index
for i := range vowels {
         fmt.Println(vowels[i])
}

Example 2: Get the index and value of slice
for i, v := range vowels {
         fmt.Printf("index %v, value %v\n", i, v)
}

App.go
package main

import "fmt"

func main() {

 var vowels = []string{"a", "e", "i", "o", "u"}

 for i := range vowels {
  fmt.Println(vowels[i])
 }

 for i, v := range vowels {
  fmt.Printf("index %v, value %v\n", i, v)
 }

}


Output
a
e
i
o
u
index 0, value a
index 1, value e
index 2, value i
index 3, value o
index 4, value u




Previous                                                 Next                                                 Home

No comments:

Post a Comment