Rust Tuple Examples (Create Tuple List)Use tuples, creating tuples and accessing items from tuples. Build up and use lists or vectors of tuples.
dot net perls
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.
Tuple syntax. 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.
Simple example. 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.
Rust program that creates tuple
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
Complex example. 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.
Part 1 We access the first tuple in the list of tuples. Here we see the type of the tuple, and how to specify it in a variable.
Part 2 We get the first item in a tuple by using the "0" property. We print the result to the screen.
Part 3 We add a tuple to the Vector of tuples. We call push(). Please notice how the list has the mut keyword, meaning it can be mutated.
Part 4 Here we loop over the tuples in our vector. This shows each key and value—which are the item 0 and item 1 parts of the tuple.
Rust program that builds up tuple list
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
A summary. Tuples are used throughout Rust programs—they are one of the foundational types. We can create and access them with a clear, simple syntax.
String Array
© 2007-2021 sam allen. see site info on the changelog