How to iterate over all map keys in Go? Iterating over a dictionary
Hello! I just started learning Go and encountered a problem when working with map. I have a dictionary that stores user names and their ages:
```go
ages := map[string]int{
"Alice": 30,
"Bob": 25,
"Charlie": 35,
}
```
I need to output all names (keys) from this map. In Python I would just write `for name in ages:`, and in JavaScript — `Object.keys(ages)`. But in Go I can't figure out how to properly iterate over all keys.
I tried using `for range`, but it returns both key and value. I only need the keys. Plus I noticed that the output order is different each time — is this normal? And what if the map is very large — won't it be slow?
Also I'm curious: is it possible to get a slice of all keys so that I can use it later, for example, for sorting?
No answers yet.
Log in to leave an answer
Blogs