If you just started learning Go, one thing will confuse you quickly:
π Arrays vs Slices
They look similar⦠but behave very differently.
Letβs break it down in the simplest way possible π
π¦ What is an Array?
An array is a fixed-size collection.
numbers := [3]int{1, 2, 3}
Key points:
- Size is fixed
- Cannot grow or shrink
- Rarely used in real-world Go apps
π What is a Slice?
A slice is a dynamic version of an array.
numbers := []int{1, 2, 3}
Key points:
- Size is dynamic
- Can grow using
append - Used almost everywhere in Go
β‘ Adding Data (Only Works with Slice)
numbers := []int{1, 2, 3}
numbers = append(numbers, 4)
Now:
[1, 2, 3, 4]
π§ Under the Hood (Important Concept)
A slice is:
- Pointer to an array
- Length
- Capacity
Think of it like:
π βA flexible view on top of an arrayβ
π Slice Example with Capacity
numbers := make([]int, 2, 5)
fmt.Println(len(numbers)) // 2
fmt.Println(cap(numbers)) // 5
β Common Mistake
arr := [3]int{1,2,3}
arr = append(arr, 4) // β ERROR
Why?
π Because arrays are fixed size
π₯ Real-World Use Case
When building APIs:
users := []string{}
users = append(users, "Ahmed")
users = append(users, "John")
Dynamic data = slices β
π§ When to Use What?
| Feature | Array | Slice |
|---|---|---|
| Size | Fixed | Dynamic |
| Usage | Rare | Common |
| Flexibility | β | β |
π In 95% of cases β use slice
π¬ Final Thought
If you understand slices, you understand how Go manages data internally.
This is a foundational conceptβdonβt skip it.
π Coming Next
Next post:
π Structs in Go (this is where real backend modeling starts)
Top comments (0)