Tuple
Often in Rust we need to store related values together. Here a tuple can be ideal—it cannot be appended to, but we can store many together in a list.
For accessing tuple items, we use a number property. This is different from arrays or vectors. We also find that tuples can be pretty-printed with println
.
When we create a tuple, we usually do not need to specify the type. Here we create a tuple with 3 items: a string
, integer and bool
.
fn main() { // Create tuple. let value = ("bird", 100, false); // Print all tuple items. println!("{:?}", value); // Print first item. let first_item = value.0; println!("{}", first_item); }("bird", 100, false) bird
Continuing on, we have a more complex example where we create a vector (list) of tuples. The tuples each have a string
and integer in them.
Vector
of tuples. We call push()
. Please notice how the list has the mut
keyword, meaning it can be mutated.fn main() { let mut list = vec![("bird", 10), ("cat", 20)]; // Part 1: get first tuple from vector. let first_items: (&str, i32) = list[0]; println!("{:#?}", first_items); // Part 2: get item from first tuple. let first = first_items.0; println!("{}", first); // Part 3: add a value to the vector, printing it before and after. println!("BEFORE: {:#?}", list); list.push(("tree", 5)); println!("AFTER: {:#?}", list); // Part 4: loop over tuples in vector. for (a, b) in list { println!("A: {}", a); println!("B: {}", b); } }( "bird", 10, ) bird BEFORE: [ ( "bird", 10, ), ( "cat", 20, ), ] AFTER: [ ( "bird", 10, ), ( "cat", 20, ), ( "tree", 5, ), ] A: bird B: 10 A: cat B: 20 A: tree B: 5
This Rust example uses more complex tuple syntax. We return a tuple from a function. In get_color_and_id
we use a match expression to return a tuple based on the argument.
main()
we call the get_color_and_id
function. We can access the 0 and 1 fields, or assign directly to them from the tuple result.fn get_color_and_id(index: usize) -> (String, i32) { match index { 1 | 2 => ("blue".to_string(), 2), _ => ("red".to_string(), 10), } } fn main() { // Get tuple, and then access its 0 and 1 fields. let result = get_color_and_id(0); println!("{} {}", result.0, result.1); // Get parts of tuple directly in assignment. let (color, id) = get_color_and_id(2); println!("{} {}", color, id); }red 10 blue 2
Tuple
argumentA tuple can be passed to a function. Tuples are always copied by value, much like an integer value. Here we pass a tuple to handle_tuple
.
fn handle_tuple(t: (usize, &str, u8)) { println!("{}, str = {}", t.0 + (t.2 as usize), t.1); } fn main() { let tuple = (100000, "RUST", 3); // Pass tuple value. handle_tuple(tuple); }100003, str = RUST
Tuples are used throughout Rust programs—they are one of the foundational types. We can create and access them with a clear, simple syntax.