Skip to main content

Go Slices

A slice feels a lot like an array, with more power and flexibility.

It also keeps many values of one type in a single variable. The big difference is size: a slice can get longer or shorter whenever you need it to, while an array cannot.

You have a few options for creating one:

  • Write the values directly, in the []datatype{values} form
  • Cut a slice out of an existing array
  • Call the make() function

Create a Slice With []datatype{values}

The most direct way to declare a slice is to list its values inside curly braces, as the syntax shows.

Two built-in functions tell you about any slice. len() gives its length, meaning how many elements it currently holds. cap() gives its capacity, meaning how many elements it has room for.

Example

Both slices below are written in this form. The first has no values, so its length and capacity are 0; the second holds four values, so both are 4:

Prompt
Create two slices using the literal syntax: one empty and one with string values. Print the length, capacity, and values of both.
Output: Go program and captured output

Syntax

main.go
slice_name := []datatype{values}

Create a Slice From an Array

Another option is to take part of an array, by giving a start and end position in square brackets.

Example

arr1[2:4] covers index 2 up to, but not including, index 4. The capacity is 4 because four elements remain in the array from index 2 onward:

Prompt
Create an array of six integers, then create a slice from index 2 to 4. Print the slice, its length, and capacity.
Output: Go program and captured output

Syntax

main.go
var myarray = [length]datatype{values} // An array
myslice := myarray[start:end]          // A slice made from the array

Create a Slice With The make() Function

Calling make() is a third way to get a slice, and it lets you choose the length and capacity.

Note: capacity is optional. Leave it out and it takes the same value as length.

Example

myslice1 gets a length of 5 and a capacity of 10. myslice2 gives no capacity, so it ends up with 5 for both:

Prompt
Create slices using the make() function: one with length and capacity, one with only length. Print values, length, and capacity.
Output: Go program and captured output

Syntax

main.go
slice_name := make([]type, length, capacity)