Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Working with Arrays | Core Collections in Go
Data Structures in Go

bookWorking with Arrays

Veeg om het menu te tonen

Understanding Arrays in Go

Arrays in Go are a core collection type that lets you store a fixed-size sequence of elements of the same type. You use arrays when you know exactly how many items you need to store, and you want them grouped together in a single variable.

Declaring Arrays

To declare an array, specify its length and the type of its elements. For example, to declare an array of five integers:

var numbers [5]int

This creates an array named numbers that can hold exactly five integers. All elements are automatically set to the zero value for their type (0 for int).

Initializing Arrays

You can initialize an array at the time of declaration by providing values in curly braces:

var primes = [4]int{2, 3, 5, 7}

You can also let Go count the number of elements for you by using ... instead of a specific length:

odds := [...]int{1, 3, 5, 7, 9}

Accessing Array Elements

Access elements in an array using zero-based indexing. The first element is at index 0, the second at 1, and so on:

fmt.Println(primes[2]) // Prints: 5

You can also assign new values to specific elements:

numbers[0] = 42

Key Points

  • Arrays have a fixed length and cannot be resized;
  • All elements must be of the same type;
  • Indexing starts at zero;
  • Arrays are value types, meaning assignments copy the entire array.

Arrays are fundamental to data organization in Go and serve as the foundation for more advanced collections like slices.

main.go

main.go

copy
1234567891011121314151617181920212223
package main import "fmt" func main() { // Declare an array of 5 integers var numbers [5]int // Initialize array elements numbers[0] = 10 numbers[1] = 20 numbers[2] = 30 numbers[3] = 40 numbers[4] = 50 // Access and print individual elements fmt.Println("First element:", numbers[0]) fmt.Println("Third element:", numbers[2]) fmt.Println("Last element:", numbers[4]) // Print the entire array fmt.Println("All elements:", numbers) }
question mark

Which statement about declaring arrays in Go is correct?

Select the correct answer

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 1. Hoofdstuk 1

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 1. Hoofdstuk 1
some-alt