Go Slice

In Go, a slice is a more flexible and powerful version of an array. Like an array, a slice is a collection of elements of the same type. However, the size of a slice can change dynamically during runtime, unlike an array.

The syntax for creating a slice in Go is as follows:

re‮:ot ref‬theitroad.com
var sliceName []dataType

Here's an example of creating a slice of integers in Go:

var numbers []int

In this example, a slice named numbers is created with element type of int. The slice is initialized to a zero value of nil, which means it doesn't yet point to an underlying array.

You can also initialize a slice with values when it is created, like this:

numbers := []int{1, 2, 3, 4, 5}

In this example, the slice numbers is created and initialized with the values 1, 2, 3, 4, and 5.

You can append elements to a slice using the append function, which takes a slice and one or more elements to add to it. Here's an example:

numbers = append(numbers, 6, 7, 8)

In this example, the values 6, 7, and 8 are appended to the numbers slice.

You can also slice a slice using the : operator, which returns a new slice that refers to a subset of the elements of the original slice. Here's an example:

subset := numbers[1:4]

In this example, the subset slice is created from the numbers slice and contains the elements at indices 1, 2, and 3 (i.e., the second, third, and fourth elements of the numbers slice).