Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Slices | Arrays and Slices
Introduction to GoLang
course content

Course Content

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

book
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:

go

index

copy
1234
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:

go

index

copy
1
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:

go

index

copy
12
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:

go

index

copy
1
arrayName[startingIndex:endingIndex + 1]

We can also store this extracted portion of the array in a variable, thus creating a slice:

go

index

copy
123
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:

go

index

copy
12345678910111213
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] }
What will be the output of the following code?

What will be the output of the following code?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt