Avatar ·

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\n

I have a map with user data:

\n\n
users := map[int]string{\n    1: "Alice",\n    2: "Bob",\n    3: "Charlie",\n    4: "Diana",\n}
\n\n

I 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.

\n\n

I tried doing this:

\n\n
var keys []int\nfor key := range users {\n    keys = append(keys, key)\n}
\n\n

This 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: