Course Content
Introduction to GoLang
Introduction to GoLang
Slices
Slices are akin to arrays, but they possess dynamic lengths, making them a more flexible alternative to arrays.
To create a slice, we utilize the same syntax as for arrays, but in this case, we omit specifying the size.
Creating a slice using the var
keyword:
Create a Slice using the :=
operator:
We can add additional elements to a slice using the append
function. The append
function returns a new slice with the appended elements, which we can then store in the original slice variable. This will become clearer with an example. The basic syntax of the append
function is as follows:
The following code demonstrates the use of the append
function:
index
randomNumbers := [] int { 1, 4, 5} fmt.Println(randomNumbers) // Output: [1 4 5] randomNumbers = append(randomNumbers, 7, 9) fmt.Println(randomNumbers) // Output: [1 4 5 7 9]
In the same way that we can access elements within an array, we can also reference portions of an array using the following syntax:
index
arrayName[startIndex:endIndex + 1]
It will extract all elements from the startingIndex
to the endingIndex
. Please note that we need to provide endingIndex + 1
. This will become clearer with an example. For example:
index
var numbers = [10] int { 2, 4, 6, 9, 10, 12, 14, 16, 17, 19 } fmt.Println(numbers[4:9]) // Output: [10 12 14 16 17]
It extracts the elements from indexes 4
to 9
, including the element at index 4
and excluding the element at index 9
, as expressed in the syntax:
index
arrayName[startingIndex:endingIndex + 1]
We can also store this extracted portion of the array in a variable, thus creating a slice:
index
var numbers = [10] int { 2, 4, 6, 9, 10, 12, 14, 16, 17, 19 } numbersPart := numbers[2:7] fmt.Println(numbersPart) // Output: [6 9 10 12 14]
It's important to note that such a slice references the portion of the array from which it was created. Consequently, any changes made in that slice will also affect the original array:
index
package main import "fmt" func main() { var pin = [4] int { 1, 2, 3, 4 } part := pin[1:3] fmt.Println(pin) // Output [1, 2, 3, 4] fmt.Println(part) // Output: [2, 3] part[0] *= 2 part[1] *= 3 fmt.Println(part) // Output [4, 9] fmt.Println(pin) // Output [1, 4, 9, 4] }
Thanks for your feedback!