Quidest?

Go slices

· Lorenzo Drumond

An array has a fixed size. A slice, on the other hand, is a dynamically-sized, flexible view into the elements of an array.

The type []T is a slice with elements of type T

It is a kind of Go type that represents an ordered collection of elements, all of the same type.

A slice literal specifies the name of the slice type, followed by some element in curly braces:

1[]string{'a', 'b', 'c',}

It is like an array literal without the length. The statement above will create the array

1[3]string{'a', 'b', 'c'}

and then build a slice that references it.

In a slice literal of some custom type, such as a struct, we don’t need to repeat that type name as part of every element literal: the compiler can infer it.

We use the square-bracket notation to refer to a particular numbered element of the slice:

1mySlice[0]

is the first element of the slice mySlice. Index starts from 0.

len is a built-in function that returns the length of a slice. append is a function that appends elements to a slice.

1func append(s []T, ...T) []T

The resulting value of append is a slice containing all the elements of the original slice plus the provided values.

If the backing array of s is too small to fit all the given values a bigger array will be allocated. The returned slice will point to the newly allocated array.

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

1var a [10]int
2
3a[low:high]

When slicing, you may omit the high or low bounds to use their defaults instead.

The default is zero for the low bound and the length of the slice for the high bound.

1var a [10]int
2
3a[0:10]
4a[:10]
5a[0:]
6a[:]

are all equivalent.

References

Next -> go-slices-length-and-capacity

Next -> slice-zero-value

Next -> creating-a-slice-with-make

#slice #array #type #data #append #structured #golang