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
Release: 2024-12-10 19:47:10
Original
619 people have browsed it

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"}
Copy after login

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)
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template