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

Tuple

Tuples

  • Group number of values with various types into one compound type.
  • Tuples have fixed length, i.e. once declared they cannot grow or shrink in size.
  • Tuple can be created as comma-separated list of values inside parentheses. Type annotation is optional.
  • An empty tuple is called unit.
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
}

Destructuring

fn main () {
    let tup = (2, 4.3, "test");
    let (x, y, z) = tup;
    println!("Value of z is: {z}.");
}

Element Access

  • A tuple element can be accessed directly by using a period . followed by the index of the value we want to access (first index in a tuple is 0).
fn main() {
    let x: (i32, f64, u8) = (500, 6.4, 1);
    let five_hundred = x.0;
    let six_point_four = x.1;
    let one = x.2;
}