Okay, so I was messing around with Go again today, trying to get a better handle on how to work with maps. I decided to tackle the problem of getting all the keys from a map, which, you know, sounds simple enough, but it’s good practice.
I started by creating a simple map. Nothing fancy, just a map of strings to integers:
myMap := map[string]int{
"apple": 1,
"banana": 2,
"orange": 3,
My initial thought was, “There’s gotta be a built-in function for this, right?” Like, a `.keys()` method or something. Nope! Turns out, Go doesn’t have a direct way to just grab all the keys. You gotta do a little bit of manual work.
So, I remembered that you can iterate through a map using a `for…range` loop. That seemed like the way to go. I set up a loop like this:
keys := []string{} // Create an empty slice to store the keys.
for k := range myMap {
keys = append(keys, k) //append key into keys.
I created an empty slice called `keys` to hold the, well, keys. Then, the `for…range` loop iterates over `myMap`. Inside the loop, `k` gets assigned to each key, one at a time. I used the `append` function to add each key to my `keys` slice. Pretty straightforward.
After the loop finished, I wanted to see if it actually worked. So, I printed out the `keys` slice:
*(keys)
And boom! There they were, all the keys from my map: `[apple banana orange]`. Success!
It is a simple pratical, I think it is basic skill for using map in Go. Using `for…range` is a good way to get keys.