Go Basics

Go Slices

Description

Slices are an abstraction over arrays. They are a dynamically-sized, flexible view into the elements of an array. In practice, slices are much more common than arrays.

Pros & Cons

✅ Pros

  • Dynamic: Can grow using `append`.
  • Reference: Protecting the underlying array efficiently.

❌ Cons

  • Nil Slices: Need to check for nil in some cases (though nil slices are valid and behave like empty ones).

When to Use

Handling lists, buffers, and collections of data.

Example

Creating, slicing, and appending.

// Create a slice
primes := []int{2, 3, 5, 7, 11, 13}

// Slice it (like python)
var s []int = primes[1:4] // [3 5 7]

// Append
s = append(s, 17, 19)

Best Practices

A nil slice has a length and capacity of 0 and has no underlying array.

← Go ArraysGo Operators →