WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Basic · question 10 of 100

What are tuples in Rust, and how are they used?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, a tuple is a collection of values of different types. Tuples are similar to arrays but differ in their flexibility because they can hold different types of values.

Tuples are defined using parentheses ‘()‘ and the values inside are separated using commas ‘,‘. Here’s an example of defining a tuple:

    let my_tuple = (42, "hello", 3.14);

In this example, ‘my_tuple‘ is assigned a tuple containing three values of different types: an integer with value ‘42‘, a string with value ‘"hello"`, and a floating-point number with value ‘3.14‘.

You can access the elements of a tuple using indexing, which starts at 0. Here’s an example:

    let my_tuple = (42, "hello", 3.14);
    
    println!("{}", my_tuple.0); // prints 42
    println!("{}", my_tuple.1); // prints "hello"
    println!("{}", my_tuple.2); // prints 3.14

In this example, we access the first, second, and third elements of the tuple using the dot ‘.‘ operator followed by the index of the element we want to access.

Tuples can also be used to return multiple values from a function. Here’s an example:

    fn get_name_and_age() -> (&'static str, u8) {
        ("Alice", 25)
    }
    
    let (name, age) = get_name_and_age();
    println!("Name: {}, Age: {}", name, age); // prints "Name: Alice, Age: 25"

In this example, we define a function ‘get_name_and_age‘ that returns a tuple containing a string and an unsigned integer. Then, we use pattern matching to destructure the tuple into two variables ‘name‘ and ‘age‘.

In conclusion, Tuples in Rust are a collection of values of different types, and they are used to group related data together, or to return multiple values from a function, especially when the types of these values can differ.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics