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