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.
What is a Slice?
A slice is a reference to a portion of an array.
- Dynamic size
- Reference type
- Powerful built-in support
Declaring & Initializing
Literal Initialization
Using make()
Length vs Capacity
len → number of elements
cap → total allocated space
Appending Elements
- Automatically grows capacity
Slicing an Array
Modifying Slice (Reference Behavior)
Slices share the same underlying array.
Copying Slice
Use copy() to avoid shared data.
Looping Through Slices
Using range
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 |
GoSlice of Slice (2D Slice)
Best Practices
- Use It instead of arrays
- Always reassign after
append() Usecopy()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
