Variables

Slices in Go

Slices are used to store multiple sequenced values in one variable, similar to arrays. Unlike arrays, slices can be dynamically sized.


Syntax
newSlice := make([]dataType, sliceLength, capacity) //capacity is optional
newSlice[index] = value //assigning a slice element
newSlice = append(newSlice, value) //appending an element to a slice

//subset of a slice
subslice := newSlice[lowIndex:highIndex]

Notes

A subset of a slice can be obtained by passing in a low index (inclusive) and a high index (exclusive, meaning that element will be excluded). One of the indices can be omitted. Omitting the low index will take the subset from the beginning of the slice, and omitting the high index will take the subset to the end of the slice.

The length or size of a slice can be obtained using the len(sliceName) function. The capacity can be obtained using the cap(sliceName) function.


Example
countries := make([]string, 2)
countries[0] = "Canada"
countries[1] = "United States"
countries = append(countries, "Mexico")

< Arrays   |   Maps >

© 2018 SyntaxDB. All Rights Reserved.