Go — Slices Deep-Dive in Go
📌 Covered in this chapter:
Slice header (Pointer, Length, Capacity) · make([]T, len, cap) · append() mechanics · Reslicing [start:end] · copy()
Welcome to Go — Slices Deep-Dive in Go in our Go Complete Masterclass! Master dynamic Go slices: slice headers, length vs capacity, slice allocation with make(), append mechanics, and memory reslicing.
1Slices Deep-Dive & Memory Architecture
Go lo Slice ante oka dynamically sized, flexible view into an underlying array. Slices are lightweight reference headers passing by value.
Go Slice Header Internal Memory Layout (24 bytes on 64-bit CPU):
┌────────────────────────────────────────────────────────┐
│ Pointer (8 bytes) ───> Points to underlying Array │
├────────────────────────────────────────────────────────┤
│ Length (8 bytes) ───> Current number of elements len()│
├────────────────────────────────────────────────────────┤
│ Capacity (8 bytes) ───> Maximum elements space cap() │
└────────────────────────────────────────────────────────┘
Go — Slice Allocation & append() Mechanics
▶ Run Code
package main
import "fmt"
func main() {
// 1. Create slice with make(type, len, cap)
numbers := make([]int, 3, 5)
numbers[0], numbers[1], numbers[2] = 10, 20, 30
fmt.Printf("Slice: %v | Len: %d | Cap: %d\n", numbers, len(numbers), cap(numbers))
// 2. Append elements
numbers = append(numbers, 40, 50)
fmt.Printf("Appended: %v | Len: %d | Cap: %d\n", numbers, len(numbers), cap(numbers))
// 3. Exceed capacity -> Automatic Array Reallocation (capacity doubles!)
numbers = append(numbers, 60)
fmt.Printf("Exceeded Cap: %v | Len: %d | Cap: %d\n", numbers, len(numbers), cap(numbers))
}
💻 Live Go Code Execution
Test and run this Go program in our online high-performance Go compiler environment:
Open in Online Go Compiler →