To iterate over values in a map in Go, you can use a range-based for loop. This allows you to access each value in the map.
We can iterate over values in a map in Go using a range-based for loop, which provides a convenient syntax for iterating over all values in the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.fmt.Println
function to verify that we are iterating over all values.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Iterate over values using range-based for loop
for _, value := range myMap {
fmt.Println(value)
}
}
1 2 3
We can iterate over keys and values in a map in Go using a range-based for loop, which provides a way to access both keys and values.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.fmt.Println
function to verify that we are iterating over all keys and values.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Iterate over keys and values using range-based for loop
for key, value := range myMap {
fmt.Println(key, value)
}
}
one 1 two 2 three 3
We can store values in a separate slice and then iterate over the slice in Go, which provides a way to work with values independently of their keys.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.values
to store the values from the map.values
slice.values
slice and print each value to the console using the fmt.Println
function to verify that we have stored all values separately.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Declare a slice to store the values
var values []int
// Store values in the slice
for _, value := range myMap {
values = append(values, value)
}
// Iterate over the values slice
for _, value := range values {
fmt.Println(value)
}
}
1 2 3
In this tutorial, we learned How to Iterate Over Values in a Map in Go language with well detailed examples.