Tuples

If you want to combine a certain number of values of different types, then you can collect them in a tuple, enclosed between parentheses (( )) and separated by commas, like this:

// from Chapter 4/code/tuples.rs 
let thor = ("Thor", true, 3500u32); 
println!("{:?}", thor); // ("Thor", true, 3500) 

The type of thor is (&str, bool, u32), that is, the tuple of the item's types.

To extract an item on index use a dot syntax:

println!("{} - {} - {}", thor.0, thor.1, thor.2); 

Another way to extract items to other variables is by destructuring the tuple:

let (name, _, power) = thor; 
println!("{} has {} power points ", name, power); 

This prints out the following output:

    Thor has 3500 power points  

Here the let statement matches the pattern on the left with the right-hand side. The _ indicates that we are not interested in the second item of thor.

Tuples can only be assigned to one another or compared with each other if they are of the same type. A one-element tuple needs to be written like this:

let one = (1,); 

A function that needs to return some values of different types can collect them in a tuple and return that tuple, like this:

fn increase_power(name: &str, power: u32) 
-> (&str, u32) { if power > 1000 { return (name, power * 3); } else { return (name, power * 2); } }

This function header could also be written as:

fn increase_power2((name, power): (&str, u32)) -> (&str, u32) 

If we call this with the following statement:

let (god, strength) = increase_power(thor.0, thor.2); 
println!("This god {} has now strength {} ", god, strength); 

The output looks like the following:

    This god Thor has now strength 10500  

A tuple is also very handy when swapping two variables:

let mut n = 0; 
let mut m = 1; 
let (n, m) = (m, n); 
println!("n: {} m: {}", n, m);
Exercise:
(see code in Chapter 4/exercises/tuples_ex.rs)
Try to compare the tuples (2, 'a') and (5, false), explain the error message.
Try to change an item in a tuple (hint: you must add a keyword for it to work).
Make an empty tuple.
Haven't we encountered this before? So the unit value is in fact an empty tuple!