Junior — Middle
Milline on vahe kaardi ja lõigu kasutamisel Go keeles ning millistel juhtudel on eelistatav kasutada kumbagi neist?
sobes.tech AI
Vastus AI-lt
In Go, map and slice serve different purposes:
- map — associative array, a structure for storing key-value pairs with quick access via the key. Keys are unique.
- slice — 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 want to store a set of elements without keys, for example, a task list.
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 ordered list — slice.