Slices

What is slice

Slice is a dynamic collection of elements with similar types of data.

Unlike arrays, that fixed size, slices can dynamically grow or shrink according to the requirements.

Create slice

In the above example:

  • slice is the name of slice.
  • int represents types of elements that is integers.
  • {10, 20, 30, 40, 50} is actual data of slice.

For example:

Output:

We can also create a slice using the make() function. For example,

In the above example:

  • 5 is the length of slice.
  • 7 is the capacity of the slice.

Components of slice

A slice is made up of three parts – pointer, length and capacity.

Pointer is a reference to the element of the array that is accessible through the slice. This reference can be any of elements in the array.

Length is actual number of elements in the slice.

Capacity is a total number of elements in the underlying array of the slice.

To understand it better, let’s take a look for the following example:

Empty slice equals to nil and has length 0:

Slicing

Slice also can be created from the given array.

Output:

In the above example slice created by slicing an existing array.

The first index position in a slice is always 0 and the last one will be (length of slice – 1).

Assigning one slice variable to another does not make a copy of the slices contents.

Output:

In the above example a and b shares the same underlying array. Changes in b also changed a even though b starts at a different offset.

Add elements to slice

Elements can be added to slice in the following way:

Output:

Passing slice to a function

A function that takes slice as argument can change underlying array

Output:

joonail

About Paul Smith

GoLang / PHP developer with more than 10 years experience in IT.