Photo by Marcus Dall Col on Unsplash
Looping the Collection: The Golang Way
Correct way to loop through any collection in go world
In Go we don't have forEach
keywords like JavaScript to loop through any collection instead, we use regular for
with range
keyword to work.
Example - 1
Regular Array looping
package main
import "fmt"
func main() {
favMovies := []string{"inception", "intersteller", "tenant"}
// for {key}, {value} := range {list}
for _, movie := range favMovies {
fmt.Println("My Fav movie is:", movie)
}
}
Example - 2
Likewise, if we want to loop through the Hashmap (Objects in JS echo-system) -- we can do it in the same way.
package main
import "fmt"
func main() {
myList := map[string]string{
"dog": "bark",
"cat": "meeeow",
"lion": "roar",
}
for animal, noise := range myList {
fmt.Println("The", animal, "went", noise)
}
}