Go🔧Core Languagebeginner
Arrays and Slices
Go · Core Language · Run with go run
Explanation
An array in Go has a fixed length that is part of its type: `[3]int` and `[4]int` are different types. In practice, arrays are rarely used directly — **slices** are the workhorse. A slice is a descriptor (pointer + length + capacity) over an underlying array. `make([]T, len, cap)` allocates one. `append` grows slices automatically.
Real-World Scenario
Reading lines from a file: `lines := make([]string, 0, 100)` preallocates capacity for 100 lines (avoids repeated reallocation as you append), then `lines = append(lines, line)` for each line read.
Quick Snippet
snippet.go
// Array (fixed size, value type)
arr := [3]int{1, 2, 3}
// Slice (dynamic, reference type)
s := []int{10, 20, 30}
s = append(s, 40)
// Slice of slice
sub := s[1:3] // [20, 30] — shares underlying array
// make with capacity hint
buf := make([]byte, 0, 4096)Full Example
slices.go
// Compile: go run slices.go
// Output:
// array: [1 2 3]
// slice: [10 20 30 40]
// sub: [20 30]
// len=4 cap>=4
package main
import "fmt"
func main() {
// Array — fixed size, value type
arr := [3]int{1, 2, 3}
fmt.Println("array:", arr)
// Slice — dynamic, grows with append
s := []int{10, 20, 30}
s = append(s, 40)
fmt.Println("slice:", s)
// Slicing shares the underlying array
sub := s[1:3]
fmt.Println("sub: ", sub)
fmt.Printf("len=%d cap>=%d\n", len(s), cap(s))
}
Run command
go run slices.go