ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Go (Golang) Tutorial• 7 min read

Arrays vs Slices: Dynamic View Windows

Fixed arrays [5]int vs dynamic slices []int, length, capacity, and append()

While arrays have fixed sizes, Slices are dynamic, flexible view windows layered over an underlying array, defined by a pointer, length, and capacity.

Slice Header Anatomy: Pointer, Length & Capacity

Array: [3]int{1, 2, 3} (size is part of the type; arrays cannot be resized).

Slice: []int{1, 2, 3} (resizable view).

len(s): Current number of elements in the slice.

cap(s): Total number of elements in the underlying array from the slice start.

append(slice, val): Adds elements. If capacity is exceeded, Go allocates a new doubled array automatically.

Slice Capacity and Appending
package main

import "fmt"

func main() {
    // Create slice with length 0 and pre-allocated capacity 4
    numbers := make([]int, 0, 4)
    fmt.Printf("len=%d cap=%d\n", len(numbers), cap(numbers))

    numbers = append(numbers, 10, 20, 30)
    fmt.Printf("len=%d cap=%d values=%v\n", len(numbers), cap(numbers), numbers)

    // Slice sub-window [start:end]
    sub := numbers[0:2] // [10, 20]
    fmt.Println("Subslice:", sub)
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What happens when `append()` adds an element to a slice whose length equals its capacity?