C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
But sometimes many elements, like ints or strings, are stored in an array. The elements compose a larger block of data.
Types and sizes. An array is defined by its type, its size and shape. There is no universal array, but many typed and sized arrays. We build methods that act on arrays.
An example. Let us begin with a simple example that loops over an array of three ints. We use an array initializer to create a three-element array. It contains the values 10, 20 and 30.
For: We use a for-loop to iterate over the array's elements. In this kind of for-loop, we specify a start, end, and an iteration.
Len: An array has a length. With len() we access the count of its elements—all elements are counted.
Indexes: The array is indexed starting at 0. The last index is one less than the array's total length.
Based on: Golang 1.4 Golang program that uses array package main import "fmt" func main() { // Create an array of three ints. array := [...]int{10, 20, 30} // Loop over three ints and print them. for i := 0; i < len(array); i++ { fmt.Println(array[i]) } } Output 10 20 30
Parameters. We can pass an array (specified by both element count and type) to a method. Arrays are values. They are copied when passed to a method.
Caution: This is slow. Using slices is faster. For small arrays, passing directly may be an effective approach.
Golang program that passes array as argument package main import "fmt" func display(values [3]int) { fmt.Println(values[0]) fmt.Println(values[1]) fmt.Println(values[2]) } func main() { v := [...]int{5, 10, 15} // Pass the entire array to a method. // ... This copies the array. display(v) } Output 5 10 15
Array slice, method. Usually we pass slices of arrays to methods—this avoids a copy of the elements. Here, display() receives an int array slice.
In main: We take a full-range slice of the array. The slice contains all the elements in the four-element int array.
Golang program that uses slice of array, parameter package main import "fmt" func display(values []int) { // Loop over slice argument and display elements. for i:= 0; i < len(values); i++ { fmt.Println(values[i]) } } func main() { // Create a four-element array. array := [...]int{-1, 0, 10, 100} // Pass a slice of the array to display. // ... This slice contains all elements. display(array[:]) } Output -1 0 10 100
A fundamental construct. Arrays are used as a building block, a foundation, of many things in languages. More complex collections can be built from arrays.