Go How to Convert Map to Slice with Example
for range loop to append each map key or value to the slice, like for k := range myMap { slice = append(slice, k) }.Examples
How to Think About It
for range and collect the desired elements into a new slice. This way, you gather all map entries into a list format.Algorithm
Code
package main import "fmt" func main() { myMap := map[string]int{"apple": 5, "banana": 3, "cherry": 7} var keys []string for k := range myMap { keys = append(keys, k) } fmt.Println(keys) }
Dry Run
Let's trace converting map keys to a slice with map {"apple":5, "banana":3, "cherry":7}
Initialize empty slice
keys = []
Loop over map keys
First iteration: k = "apple" Second iteration: k = "banana" Third iteration: k = "cherry"
Append keys to slice
keys after loop = ["apple", "banana", "cherry"]
| Iteration | Key | Slice after append |
|---|---|---|
| 1 | apple | [apple] |
| 2 | banana | [apple banana] |
| 3 | cherry | [apple banana cherry] |
Why This Works
Step 1: Create empty slice
We start with an empty slice to store the map keys or values because slices are dynamic arrays that can grow.
Step 2: Loop over map
Using for range lets us visit each key-value pair in the map easily.
Step 3: Append elements
Appending keys or values to the slice collects them in order, making a list from the map.
Alternative Approaches
package main import "fmt" func main() { myMap := map[string]int{"a": 1, "b": 2} var values []int for _, v := range myMap { values = append(values, v) } fmt.Println(values) }
package main import "fmt" func main() { myMap := map[string]int{"x": 10, "y": 20} keys := make([]string, 0, len(myMap)) for k := range myMap { keys = append(keys, k) } fmt.Println(keys) }
Complexity: O(n) time, O(n) space
Time Complexity
The loop visits each map element once, so time grows linearly with map size.
Space Complexity
A new slice stores all keys or values, so space also grows linearly.
Which Approach is Fastest?
Preallocating slice capacity is faster than appending without capacity because it avoids repeated memory allocation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple append | O(n) | O(n) | Quick and easy code |
| Preallocated slice | O(n) | O(n) | Better performance on large maps |
| Collect values instead of keys | O(n) | O(n) | When values are needed |
make with capacity equal to map length to optimize slice creation.