How to Create Map of Slices in Go: Syntax and Example
In Go, you create a map of slices by declaring a map where the value type is a slice, like
map[string][]int. Initialize it with make and then assign or append slices to keys as needed.Syntax
A map of slices in Go is declared by specifying the key type and a slice as the value type. For example, map[string][]int means the map keys are strings and the values are slices of integers.
You typically initialize it using make(map[string][]int) to create an empty map ready for use.
- map[keyType][]valueType: Declares a map with slice values.
- make(map[keyType][]valueType): Creates an empty map.
- Use
map[key] = []valueType{...}to assign a slice to a key. - Use
append(map[key], value)to add elements to the slice at a key.
go
var m map[string][]int m = make(map[string][]int) m["numbers"] = []int{1, 2, 3} m["numbers"] = append(m["numbers"], 4)
Example
This example shows how to create a map of slices, add slices to keys, and append values to existing slices.
go
package main import "fmt" func main() { // Create a map where keys are strings and values are slices of ints m := make(map[string][]int) // Assign a slice to a key m["primes"] = []int{2, 3, 5, 7} // Append a value to the slice at key "primes" m["primes"] = append(m["primes"], 11) // Add another key with a slice m["evens"] = []int{2, 4, 6, 8} // Print the map fmt.Println(m) }
Output
map[evens:[2 4 6 8] primes:[2 3 5 7 11]]
Common Pitfalls
One common mistake is forgetting to initialize the map with make before assigning slices, which causes a runtime panic.
Another is trying to append to a nil slice without initializing the map key first.
go
package main import "fmt" func main() { var m map[string][]int // map is nil, not initialized // This will cause a runtime panic: assignment to entry in nil map // m["numbers"] = []int{1, 2, 3} // Correct way: m = make(map[string][]int) // initialize map m["numbers"] = []int{1, 2, 3} // assign slice // Append to slice at key (works even if slice is nil) m["numbers"] = append(m["numbers"], 4) fmt.Println(m) }
Output
map[numbers:[1 2 3 4]]
Quick Reference
- Declare:
var m map[string][]int - Initialize:
m = make(map[string][]int) - Assign slice:
m["key"] = []int{1,2,3} - Append value:
m["key"] = append(m["key"], 4) - Access slice:
slice := m["key"]
Key Takeaways
Always initialize your map of slices with make before use to avoid runtime errors.
Declare the map with slice values using syntax like map[string][]int.
Use append to add elements to slices stored as map values safely.
Assign slices directly to map keys or append to existing slices as needed.
Access slices by key to read or modify the stored slice values.