Home >Backend Development >Golang >How Do I Iterate Through Keys in a Go Map?

How Do I Iterate Through Keys in a Go Map?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-10 19:47:10614browse

How Do I Iterate Through Keys in a Go Map?

Traversing Keys in a Go Language Map

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:

  • k represents the key.
  • v represents the value associated with the key.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn