0
0
GoHow-ToBeginner · 2 min read

Go How to Convert Map to Slice with Example

To convert a map to a slice in Go, create an empty slice and use a for range loop to append each map key or value to the slice, like for k := range myMap { slice = append(slice, k) }.
📋

Examples

Inputmap[string]int{"a":1, "b":2}
Output["a", "b"]
Inputmap[int]string{1:"x", 2:"y", 3:"z"}
Output[1, 2, 3]
Inputmap[string]int{}
Output[]
🧠

How to Think About It

To convert a map to a slice, think about what you want in the slice: keys, values, or both. Then, loop over the map using for range and collect the desired elements into a new slice. This way, you gather all map entries into a list format.
📐

Algorithm

1
Create an empty slice to hold the map elements.
2
Loop over the map using <code>for range</code>.
3
For each iteration, append the key or value to the slice.
4
After the loop, return or use the filled slice.
💻

Code

go
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)
}
Output
[apple banana cherry]
🔍

Dry Run

Let's trace converting map keys to a slice with map {"apple":5, "banana":3, "cherry":7}

1

Initialize empty slice

keys = []

2

Loop over map keys

First iteration: k = "apple" Second iteration: k = "banana" Third iteration: k = "cherry"

3

Append keys to slice

keys after loop = ["apple", "banana", "cherry"]

IterationKeySlice after append
1apple[apple]
2banana[apple banana]
3cherry[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

Convert map values to slice
go
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)
}
This collects map values instead of keys; useful when values are needed.
Preallocate slice length
go
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)
}
Preallocating slice capacity improves performance by reducing memory reallocations.

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.

ApproachTimeSpaceBest For
Simple appendO(n)O(n)Quick and easy code
Preallocated sliceO(n)O(n)Better performance on large maps
Collect values instead of keysO(n)O(n)When values are needed
💡
Use make with capacity equal to map length to optimize slice creation.
⚠️
Trying to convert map directly to slice without looping causes errors because maps and slices are different types.