What is an Array?
This lesson briefly defines arrays, their types, and the difference between one-dimensional and two-dimensional arrays. It also goes over how arrays are stored in memory. In this lesson, you will revise the basic concepts of *arrays* and go through some practical examples to understand this simple yet powerful data structure.
Introduction
An array is a collection of items of the same type stored contiguously in memory. It is the simplest and most widely used data structure. Most of the other data structures like stack and queues can be implemented using the array structure. This makes the array one of the central building blocks of all data structures.
Look at the figure below; you have made a simple array with four elements. Each item in the collection is called a data element, and the number of data elements stored in an array is known as its size.
Declaring arrays
A generic definition of a one-dimensional array is given below:
let arrayName: [datatype; len];
For example:
let array1: [u8; 10];
This declares array1
as an array of 10 unsigned 8 bit integers.
Initializing arrays
Arrays can be assigned values when they are declared. This is called array initialization. An example of array initialization is:
let array1: [i32;4] = [1,2,3,4]
When initializing arrays, the size can be skipped. In such cases, the compiler determines the size of the array from the list of values. The following is just as correct as the last example:
let array1 = [1,2,3,4];
There are no default values set for elements in an array. You can however set all the elements of an array to 0 or any other number, like this
let array1: [i32; 10] = [0;10];
This will initialize all the elements in the array to 0.