GO Tutorial



SLICES IN GO


Slices in Go

In Go, slices are a powerful and flexible way to work with sequences of elements. Unlike arrays, slices are dynamically sized and provide many convenient features for handling collections of data.

What is a Slice?

A slice is a descriptor of an array segment. It consists of:

  • A pointer to the underlying array
  • The length of the segment
  • The capacity of the slice (maximum length before reallocating)

Unlike arrays, slices don’t have a fixed size, so they can grow or shrink as needed.

Declaring Slices

var numbers []int        // Declares a slice of ints, initially nil
colors := []string{"red", "green", "blue"}  // Declares and initializes a slice
  

Creating Slices with make()

You can create slices with a specified length and capacity using make():

s := make([]int, 5)        // Length 5, capacity 5, all elements initialized to 0
s2 := make([]int, 3, 10)   // Length 3, capacity 10
  

Accessing and Modifying Elements

You can access or update slice elements using indices:

colors := []string{"red", "green", "blue"}
fmt.Println(colors[1])    // Output: green

colors[2] = "yellow"      
fmt.Println(colors)       // Output: [red green yellow]
  

Slicing Slices

You can create new slices by slicing existing slices or arrays:

nums := []int{1, 2, 3, 4, 5}
subslice := nums[1:4]     // Elements from index 1 to 3 β†’ [2 3 4]
fmt.Println(subslice)
  

Appending to Slices

You can add elements dynamically using the built-in append() function. If the slice’s capacity is exceeded, Go automatically allocates a new underlying array.

var nums []int            // nil slice
nums = append(nums, 1)    // [1]
nums = append(nums, 2, 3) // [1 2 3]
fmt.Println(nums)
  

Length and Capacity

Use len() to get the number of elements and cap() for the capacity of the slice:

s := make([]int, 3, 5)
fmt.Println("Length:", len(s))   // 3
fmt.Println("Capacity:", cap(s)) // 5
  

Important Notes

  • Slices share the underlying array. Changing an element in one slice can affect other slices sharing that array.
  • A nil slice behaves like an empty slice when reading, but you cannot assign to it without initialization.
  • Use append() to grow slices dynamically.

Summary

Slices are the idiomatic way to work with collections in Go. They offer flexibility, dynamic sizing, and convenient built-in functions that make them more powerful than arrays in most cases.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review