Premium Tutorials • Books • Articles • Modern Programming Paths Go Programming Book · Author Bookstore
Lesson 9 of 15

Arrays, Slices, and Maps

Store multiple values using arrays, slices, and maps.

Beginner Friendly Runnable Example Go Programming
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

  1. Create a slice of five numbers.
  2. Append a new item to a slice.
  3. 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.