Junior — Middle
What is the difference between using a map and a slice in Go, and in which cases is it preferable to use each of them?
sobes.tech AI
Answer from AI
In Go, map and slice serve different purposes:
- map — an associative array, a structure for storing key-value pairs with fast access by key. Keys are unique.
- slice — a dynamic array, an ordered collection of elements, accessed by index.
When to use:
- Use map if you need to quickly find elements by a unique key, for example, storing users by ID.
- Use slice if the order of elements is important, or you need to store a set of elements without keys, for example, a list of tasks.
Example:
// map for storing student grades by name
grades := map[string]int{"Alice": 90, "Bob": 85}
// slice for storing a list of names
names := []string{"Alice", "Bob", "Charlie"}
The choice depends on the task: for key-based lookup — map, for an ordered list — slice.