20. Arrays
collecting similar data
Array Type
Arrays are one of the fundamental type in any programming languages. Arrays are generally used to store list of things of similar type.
In Go, an array is a fixed-length sequence of zero or more elements of a particular type. That means, at run-time array can not grow or shrink. Due to this limitation, arrays are rarely used directly in Go
Declaring array
While declaring array, we need to specify size and type of array.
Below are some of array declarations:
1st line declares array named numbers
which can hold up-to 8 float64
values.
2nd declares array named songs
which can hold up-to 5 string
values
Accessing array elements
Since an array is collection of item, individual items of an array can be accessed by using square brackets []
with an index that begins at 0
Remember array index starts at 0
and not 1
If we try to access an element out or array index, Go compiler will give us error
output: invalid array index 7 (out of bounds for 7-element array)
Zero Values
When a new array is created, all the values are initialized to the zero value for the type. Zero Values ensures that array is not uninitialized.
Array Literals
We can assign values to an array while declaring using Array Literals.
Short variable declaration can also be used for array declaration
Ellipsis
if an ellipsis “...
” appears in place of the length, the array length is determined by the number of elements
Iterating over Array
We can use traditional index to iterate over an array.When accessing array elements using a index variable, we need to be careful. Trying to access an index that is outside the array will cause a run-time panic!
A safer way is to use len()
function to calculate length of array being iterated.
A more idiomatic way is to use for...range
to loop over an array. range
returns each array index and item.
If index is not required, it can be ignored using blank identifier
Type Of Array
Type of array is determined by what type of data array stores as well as length of array. If two array's store same type of data but have different lengths, Go will treat those arrays as of two different types.
Comparing Arrays
Arrays of similar types can be compared using ==
and !=
. Remember, for arrays to be to of similar types, they need to store same type of data as well as their length must be same.
GitHub Code
Blog Posts
Last updated