Working with Arrays
Glissez pour afficher le menu
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
1234567891011121314151617181920212223package 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) }
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion