Module 1: Slices (The Dynamic Tray)
π Module 1: Slices
Course ID: GO-105
Subject: The Dynamic Tray
In Go, we rarely use fixed-size arrays. We use Slices. A slice is like a tray that can stretch or shrink as you add more items.
ποΈ Step 1: The Stretch Rule
π§© The Analogy: The Magic Tray
- Imagine you have a tray for 3 cookies.
- You want to add a 4th cookie.
- In some languages, youβd have to throw away the tray and buy a new one.
- In Go, the Slice automatically buys a bigger tray for you and moves your cookies over!
ποΈ Step 2: Slice Operations
- Creation:
mySlice := []int{1, 2, 3} - Adding:
mySlice = append(mySlice, 4) - Slicing:
half := mySlice[0:2](Taking a portion of the tray).
π₯ Module 1 Review
- Slice: A dynamic array that grows automatically.
- Append: The most important tool for adding data.
- Length vs Capacity: How many items are there vs. how many could fit.
:::tip Slow Learner Note When you use append, always re-assign the result: slice = append(slice, val). It ensures you donβt lose your cookies when the tray stretches! :::