Go Slices

Go Tutorial

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

FeatureNil SliceEmpty Slice
ValuenilNot nil
Length00
MemoryNo allocationAllocated

 GoSlice of Slice (2D Slice)


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

You may also like...