Go Slices

Slices in Go are similar to arrays but more dynamic and versatile. While both store multiple values of the same data type in a single variable, slices differ because their lengths can grow or shrink as needed, unlike arrays with fixed lengths.

Tutorials dojo strip



Creating a Slice

There are three primary ways to create a slice in Go:

  1. Using the []datatype{values} format
  2. Creating a slice from an array
  3. Using the make() function




Creating a Slice Using []datatype{values}

To declare a slice with this method:

Syntax:

Go

For instance:

Go

The code above creates an empty slice with both a length and capacity of 0.

To initialize a slice during its declaration:

Go

This example declares a slice with a length and capacity of 3.




Go provides two essential functions for slice handling:

  • len() returns the number of elements in the slice.
  • cap() returns the capacity of the slice, i.e., the maximum number of elements it can grow to.

Example:

Go

Output:

Go

Here, the first slice is empty, so its length and capacity are 0. The second slice includes elements, so the length and capacity correspond to the number of those elements.




Creating a Slice from an Array

Slices can be derived from arrays by specifying a range of elements.

Syntax:

Go

Example:

Go

Output:

Go

In this case:

  • recentYears is a slice of length 2, derived from the array motorcycleYears.
  • It starts from the third element (index 2) and ends before the fifth element (index 4).
  • The slice’s capacity is 4 because it can grow from its starting point to the end of the array.




Creating a Slice Using the make() Function

The make() function is a powerful tool for creating slices with pre-defined lengths and capacities.

Syntax:

Go

Note: If the capacity parameter is omitted, it defaults to the length.

Example:

Go

Output:

Go

Here:

  • The first slice has a length of 5 and capacity of 10.
  • The second slice’s length and capacity are both 5, as the capacity parameter is omitted.

Tutorials dojo strip