A map in Go language stores key-value pairs, where keys are unique identifiers associated with their respective values. To iterate through all the keys in a map, several approaches can be utilized.
For instance, suppose we have a map defined as follows:
m := map[string]string{"key1": "val1", "key2": "val2"}
Using a Range-Based Loop:
This is the most straightforward method for iterating over both keys and values:
for k, v := range m { fmt.Printf("key[%s] value[%s]\n", k, v) }
In this loop:
If you're not interested in retrieving the value, you can omit the second variable, as seen here:
for k := range m { fmt.Printf("key[%s]\n", k) }
The above is the detailed content of How Do I Iterate Through Keys in a Go Map?. For more information, please follow other related articles on the PHP Chinese website!