Tuples
Rust tuples have a lot in common with Haskell tuples. They are both heterogeneous sequences of unnamed fields. They are created using parenthesized lists:
let bingo_call: (char, u8) = ('B', 13);
let character = ("Tom Nook", TANUKI, Month::May, 30);
They may be destructured in a let
statement:
let (name, species, month, day) = character;
If we are iterating through a collection of tuples, we may destructure each tuple directly in the for-in loop iterator. This code iterates through the index-value pairs generated by enumerate
:
let members = ["Ponyboy", "Johnny", "Dallas"];
for (index, member) in members.iter().enumerate() {
println!("{} -> {}", index, member);
}
Destructuring is one way to get at the tuple fields. Another way is to use an indexing expression. Fields aren't named in a tuple, so we access them via their index:
println("name: {}", character.0);
println("species: {}", character.1);
When indexing into a list, the index is computed dynamically, as in xs[i * 2 + 1]
. Dynamic indices are not legal in tuples. The index in an index expression must be an integer literal. The compiler needs to know what field is being accessed so it can perform typechecking.