AnyCompiler

Arrays and Slices

An array has a fixed size that's part of its type — [3]int and [5]int are different types entirely. Arrays exist in Go, but they're used far less often than slices in everyday code.

package main

import "fmt"

func main() {
	var grid [3]int
	grid[0] = 10
	grid[1] = 20
	grid[2] = 30
	fmt.Println(grid, len(grid))
}
Output
[10 20 30] 3

Slices: Go's go-to collection

A slice is a flexible, growable view over an underlying array — append() adds an item (growing the underlying storage automatically if needed), and slicing with [start:end] gives you a view over a range without copying the data.

package main

import "fmt"

func main() {
	fruits := []string{"apple", "banana", "cherry"}
	fruits = append(fruits, "date")
	fmt.Println(fruits)

	firstTwo := fruits[0:2]
	fmt.Println(firstTwo)
}
Output
[apple banana cherry date]
[apple banana]

Next: maps — Go's built-in key-value collection, and the comma-ok idiom for checking if a key exists.

Practice exercise

Create a slice numbers := []int{4, 8, 15, 16}, use append to add 23, then print the slice.