Start learning free

LESSON 267 OF 679 · TUPLES, SORTING & BUILT-INS

Tuples in Rust

Lesson

TL ; DR:

A tuple keeps a few values together, like a movie's title and year. Read them with .0 and .1, or unpack them into variables.


let movie = ("Frozen", 2013);     // a tuple

println!("{}", movie.0);          // Frozen

println!("{}", movie.1);          // 2013

let (title, year) = movie;        // unpacking

println!("{} {}", title, year);   // Frozen 2013


Full lesson:

Some values belong together. A movie has a title and a year. A point has an x and a y. A tuple keeps a few values like these in one variable.

  • ("Frozen", 2013) makes a tuple. Its type is (&str, i32).
  • movie.0 is the first value, "Frozen". movie.1 is the second, 2013. Use a dot, not square brackets.
  • {:?} prints a whole tuple, as it prints a vector: ("Frozen", 2013).

let (title, year) = movie; unpacks the tuple into two new variables. It works like for (name, points) in &scores.

A function can return a tuple. Its return type is the tuple's type, like (i32, i32). Then return (a, b); builds it.

A tuple made with let can't be changed, like any Rust value. With let mut, movie.1 = 2014 works. Still, a tuple never gets more values, and its types stay fixed.


Your task

Rex the dog went for a long walk. pet holds his name and his age.

First, make split_time return its tuple: the whole hours and the minutes left.

Then unpack pet into name and age.

Last, call split_time(135). Unpack its result into hours and mins.

The code already prints the three lines.

Expected output:

Rex
Rex is 4
Rex walked 2 h 15 min
STEP 1 OF 3
    Ctrl + Enter to check