Matching on a tuple

⚓ Rust    📅 2025-10-31    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Matching on a tuple

I am confused as to why I am allowed to match to Some(ref mut y) in the first match statement if it's not actually a &mut in the tuple. Can someone please explain what is going on here so I can learn?

struct A {
    x: Option<i32>,
}

fn main(){
    let mut a = A{ x: Some(1) };
    let b: &mut A = &mut a;
    
    let o: Option<i32> = None;
    
    match (b.x, o) {
        (Some(ref mut y), None) =>{
            println!("y was {}", y);
            *y +=1;
            println!("y is now {}", y);
        },
        _ => {}
    }
 
    match b.x {
        Some(ref mut y) =>{
            println!("y was {}", y);
            *y +=1;
            println!("y is now {}", y);
        },
        _ => {}
    }

    println!("a.x={:?}", a.x);
}

Output:

y was 1
y is now 2
y was 1
y is now 2
a.x=Some(2)

Rust Playground Link

6 posts - 2 participants

Read full topic

🏷️ Rust_feed