Destructuring Tuples in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to destructure tuples in Rust using the match statement. The example code demonstrates different patterns for destructuring tuples, such as extracting specific elements, ignoring certain elements, and using the wildcard _ to indicate that the value doesn't matter.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") subgraph Lab Skills rust/variable_declarations -.-> lab-99310{{"`Destructuring Tuples in Rust`"}} rust/string_type -.-> lab-99310{{"`Destructuring Tuples in Rust`"}} rust/function_syntax -.-> lab-99310{{"`Destructuring Tuples in Rust`"}} rust/expressions_statements -.-> lab-99310{{"`Destructuring Tuples in Rust`"}} rust/lifetime_specifiers -.-> lab-99310{{"`Destructuring Tuples in Rust`"}} end

tuples

Tuples can be destructured in a match as follows:

fn main() {
    let triple = (0, -2, 3);
    // TODO ^ Try different values for `triple`

    println!("Tell me about {:?}", triple);
    // Match can be used to destructure a tuple
    match triple {
        // Destructure the second and third elements
        (0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z),
        (1, ..)  => println!("First is `1` and the rest doesn't matter"),
        (.., 2)  => println!("last is `2` and the rest doesn't matter"),
        (3, .., 4)  => println!("First is `3`, last is `4`, and the rest doesn't matter"),
        // `..` can be used to ignore the rest of the tuple
        _      => println!("It doesn't matter what they are"),
        // `_` means don't bind the value to a variable
    }
}

Summary

Congratulations! You have completed the Tuples lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like