Arrays

Arrays are simple to construct. For example:

let my_array = ["Merseybus", "Amberline", "Crosville", "Liverbus", "Liverline", "Fareway"]; 

Arrays must comply with a number of rules, which are as follows:

  • The array has a fixed size. It can never grow as it is stored as a continuous memory block.
  • The contents of the array can only ever be of one type.

As with any type of variable, by default arrays are non-mutable. Even if the array is mutable, the overall size cannot be changed. For example, if an array has five elements, it cannot be changed to six.

We can also create an array with a type, as follows:

let mut my_array_two: [i32; 4] = [1, 11, 111, 1111]; 
let mut empty_array: [&str; 0] = []; 

It is also possible to create an array a number of times with the same value, as follows:

let number = [111; 5]; 

This will create an array called number with 5 elements, all initialized to a value of 111.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset