How to get a slice of keys from a map in Go: a complete guide
Hello everyone! I recently started learning Go and encountered a problem that seems elementary, but I can't find an elegant solution.
\n\nI have a map with user data:
\n\nusers := map[int]string{\n 1: "Alice",\n 2: "Bob",\n 3: "Charlie",\n 4: "Diana",\n}\n\nI need to get a list of all user IDs (keys) as a []int slice. In Python I would just write list(users.keys()), but in Go there is no such simple function.
I tried doing this:
\n\nvar keys []int\nfor key := range users {\n keys = append(keys, key)\n}\n\nThis works, but it seems too verbose to me. Maybe there is a built-in function or a more idiomatic way? I'm especially concerned about:
No answers yet.
Log in to leave an answer