How to get a slice of keys from a map in Go: a simple and efficient solution
Hello everyone! I'm a beginner Go developer and I've encountered what seems like a simple task, but I can't find an elegant solution.\n\nI have a map, let's say `map[string]int`, where the keys are usernames and the values are their ages. I need to get a list of all keys (names) as a slice `[]string` to, for example, pass it to a function that displays a list of users.\n\nIn Python, I would just write `list(my_dict.keys())`. In JavaScript — `Object.keys(myObj)`. But in Go, so far I only see the option with manual iteration:\n\n```go\nusers := map[string]int{\n "Alice": 25,\n "Bob": 30,\n "Charlie": 22,\n}\n\nvar keys []string\nfor k := range users {\n keys = append(keys, k)\n}\n```\n\nThis works, but it looks like a verbose reinvention of the wheel. It seems to me that for such a frequently
No answers yet.
Log in to leave an answer
Blogs