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

How Do I Iterate Through Map Keys in Go?

Susan Sarandon
Release: 2024-12-19 22:41:15
Original
111 people have browsed it

How Do I Iterate Through Map Keys in Go?

How to Iterate through Map Keys in Go

In the Go programming language, maps are unordered collections of key-value pairs. You can determine the number of elements in a map using the len() function. However, accessing and manipulating individual keys and values requires a different approach.

To iterate over all the keys in a map, use the range statement. This statement allows you to sequentially access both the key and the corresponding value for each element in the map.

For example, consider the following map:

m := map[string]string{"key1": "val1", "key2": "val2"}
Copy after login

To iterate over the keys in this map, you can use the following code:

for k, v := range m {
    fmt.Printf("key[%s] value[%s]\n", k, v)
}
Copy after login

In this code, the k variable represents the key, and the v variable represents the value associated with that key. The fmt.Printf() function is used to print the key and value in a specific format.

Another option for iterating over map keys is to use the following simplified syntax:

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Copy after login

In this case, the k variable represents the key, and you can access the corresponding value using the m[k] expression.

It's important to note that the order of key iteration is arbitrary in Go maps. This means that the keys may not be iterated over in the same order in which they were inserted.

The above is the detailed content of How Do I Iterate Through Map Keys in Go?. 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