Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Array

Arrays

  • Group number of values with the same types into one compound type.
  • Arrays have fixed length, i.e. once declared they cannot grow or shrink in size.
  • Array can be created as as a comma-separated list inside square brackets.
  • Type annotation is written using square brackets with the type of each element, a semicolon, and then the number of elements in the array.
fn main() {
    let a = [1, 2, 3, 4, 5];
    let b: [i32; 5] = [1, 2, 3, 4, 5]; // with explicit type annotation
    let c = [3; 5]; // equivalent to let c = [3, 3, 3, 3, 3];
}

Element Access

fn main() {
    let a = [1, 2, 3, 4, 5];

    let first = a[0];
    let second = a[1];
}