CodeBlanks Logo Icon CodeBlanks

Tuple

Group different types in a single value with a tuple.

Tuples

A tuple holds a fixed number of values of different types together. Elements are reached with .0, .1, or destructured with let:

let kisi: (&str, u32, bool) = ("Ada", 36, true);
println!("{}", kisi.0);           // Ada
let (ad, yas, _) = kisi;
println!("{ad} {yas}");

A tuple is the easiest way to return several values from a function: fn min_max(...) -> (i32, i32).

Returning a tuple

A function that returns the quotient and remainder together:

fn bol(a: i32, b: i32) -> (i32, i32) {
    (a / b, a % b)
}

let (bolum, kalan) = bol(17, 5);
println!("{bolum} {kalan}");  // 3 2

For larger data whose elements have meaning, a struct with named fields is preferred over a tuple; what kisi.1 means is forgotten over time.

Practice Quotient and remainder

Write the fn bol(a: i32, b: i32) -> (i32, i32) function. Destructure with let (q, r) = bol(17, 5); and print println!("{q} {r}");.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn bol(a: i32, b: i32) -> (i32, i32) {
    (a / b, a % b)
}

fn main() {
    let (q, r) = bol(17, 5);
    println!("{q} {r}");
}

Expected output

3 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the empty tuple <code>()</code> represent?

  • null
  • An empty array
  • "No value"; the unit type Correct answer
  • An error

Explanation: Functions that return no value actually return (); println! returns () too.

2 Second element

Question
let nokta = (3, 7);
println!("{}", nokta.____);  // 7
Answer
let nokta = (3, 7);
println!("{}", nokta.1);  // 7

Explanation: Tuple elements are read with .0, .1, starting at 0.

3 Expression and result

Term Meaning
(1, "a").1 "a"
let (x, _) = (5, 6) x = 5
() Unit type
(a / b, a % b) Returns two values

All lessons in Beginner