Arrays, Slices, and Maps
Store multiple values using arrays, slices, and maps.
Learning objective: Use slices and maps to manage collections of values.
Arrays
An array stores a fixed number of values of the same type. Arrays are useful but less flexible than slices.
Slices
A slice is a flexible collection that can grow. Most beginner Go programs use slices more often than arrays.
Maps
A map stores key-value pairs. It is useful when you want to look up a value by a name, ID, or key.
Example Code
Create or update your Go file, then run the program using go run main.go.
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30}
numbers = append(numbers, 40)
scores := map[string]int{
"Ali": 85,
"Mei": 92,
"John": 78,
}
fmt.Println(numbers)
fmt.Println("Mei's score:", scores["Mei"])
}
Key points to remember
- Use append to add items to a slice.
- Map keys must be comparable types such as string or int.
- Access a map value using square brackets.
Practice Exercises
- Create a slice of five numbers.
- Append a new item to a slice.
- Create a map of product names and prices.
Continue Learning
After this lesson, continue to the next lesson or explore related tutorials on VisualStudioTutor.com.