Go Slices
Go (Golang) – Slices
Slices are one of the most important data structures in Go.
They are dynamic, flexible, and built on top of arrays.
In real-world Go programs, slices are used far more often than arrays.
1️⃣ What is a Slice?
A slice is a reference to a portion of an array.
✔ Dynamic size
✔ Reference type
✔ Powerful built-in support
2️⃣ Declaring & Initializing
Literal Initialization
Using make()
3️⃣ Length vs Capacity
-
len → number of elements
-
cap → total allocated space
4️⃣ Appending Elements
✔ Automatically grows capacity
5️⃣ Slicing an Array
6️⃣ Modifying Slice (Reference Behavior)
Slices share the same underlying array.
7️⃣ Copying Slices
Use copy() to avoid shared data.
8️⃣ Looping Through Slices
Using range
9️⃣ Removing Elements from Slice
Remove element at index i
🔟 Nil vs Empty
| Feature | Nil Slice | Empty Slice |
|---|---|---|
| Value | nil |
Not nil |
| Length | 0 | 0 |
| Memory | No allocation | Allocated |
1️⃣1️⃣ GoSlice of Slices (2D Slice)
1️⃣2️⃣ Best Practices
✔ Use It instead of arrays
✔ Always reassign after append()
✔ Use copy() when isolation needed
✔ Be careful with slicing shared arrays
Summary
-
Its are dynamic & flexible
-
Built on arrays
-
Share underlying memory
-
Core data structure in Go
