Go Slices and Maps Explained
Edited by Dev Kilaru, Senior Data Analyst. How we make our content
Introduction
Slices and maps are the workhorse collections in Go. A slice is a flexible, ordered view onto an array, and a map stores key-value pairs. This tutorial shows how to create, grow, loop over, and safely use both.
Prerequisites
- Go installed
- Basic Go syntax: variables and functions
Step-by-Step Guide
Step 1: Create and grow a slice
A slice literal has no size between the brackets. append returns the updated slice, so always assign the result back.
nums := []int{1, 2, 3}
nums = append(nums, 4, 5)
fmt.Println(nums, len(nums)) // [1 2 3 4 5] 5Step 2: Slice a slice
The expression s[low:high] includes low and excludes high. The new slice shares the same underlying array, so changes to one can show up in the other.
part := nums[1:3]
fmt.Println(part) // [2 3]Step 3: Create and use a map
Maps are created with a literal or make. Reading a missing key returns the zero value, so use the two-value form to check whether it exists.
ages := map[string]int{"Ava": 30, "Ben": 25}
ages["Cy"] = 41
age, ok := ages["Dee"]
if !ok {
fmt.Println("Dee not found")
}
fmt.Println(age) // 0 (zero value)Step 4: Delete entries and loop with range
delete removes a key. range gives the index and value for slices, and the key and value for maps. Map iteration order is random by design.
delete(ages, "Ben")
for i, n := range nums {
fmt.Println(i, n)
}
for name, age := range ages {
fmt.Println(name, age)
}FAQs
- What is the difference between an array and a slice in Go?
- An array has a fixed length that is part of its type. A slice is a dynamically sized view onto an array and is what you'll use in most code.
- Can I rely on the order of items in a map?
- No. Go deliberately randomizes map iteration order. If you need a stable order, collect the keys into a slice and sort them.
Summary
Use slices for ordered data and maps for lookups by key. Remember to assign the result of append, and use the comma-ok form to tell a missing map key from a zero value.
Related tutorials
- Schedule and Debug Shell Scripts: cron, bash -x, and Portability
- Shell Scripting Project: A Backup Script with Rotation and a Log Report
- Writing Safe Bash Scripts: set -euo pipefail, getopts, and trap
- Shell Pipes, Redirection, grep, sed, and awk for Text Processing
- Bash Loops, Arrays, and Functions Explained
Comments
Log in or create a free account to join the discussion.