Rust Tuple

In Rust, a tuple is a collection of values of different types. Tuples are an ordered list of elements enclosed in parentheses. Here's an example of a tuple containing two elements:

let my_tuple = (1, "hello");

println!("Tuple: {:?}", my_tuple);
‮w:ecruoS‬ww.theitroad.com

In this example, we're creating a tuple with two elements: an integer with the value 1 and a string with the value "hello". We're then printing the tuple using the println! macro.

You can access individual elements of a tuple using pattern matching or by using the dot notation with the index of the element. Here are two examples:

let my_tuple = (1, "hello");

let (num, greeting) = my_tuple;
println!("Number: {}", num);
println!("Greeting: {}", greeting);

let my_tuple = (1, "hello");

println!("Number: {}", my_tuple.0);
println!("Greeting: {}", my_tuple.1);

In the first example, we're using pattern matching to extract the individual elements of the tuple and store them in separate variables. We're then printing the values of those variables.

In the second example, we're accessing the individual elements of the tuple using the dot notation and the index of the element (starting from 0).

Tuples can be useful when you want to return multiple values from a function, for example:

fn get_name_and_age() -> (&'static str, u32) {
    ("Alice", 30)
}

let (name, age) = get_name_and_age();
println!("Name: {}, Age: {}", name, age);

In this example, we're defining a function get_name_and_age that returns a tuple containing a string and an integer. We're then calling the function and storing the returned values in separate variables using pattern matching. Finally, we're printing the values of those variables using the println! macro.