Search code examples
rust

match expression with initializers


Can we have initializers in the match expression just like C++ if statement with initializers if statement initializers. The reason I'm asking is because the below code is resulting in deadlock and I thought of resolving this deadlock issue using initializers like the commented code below.

use std::sync::{Arc, Mutex};

struct A {
    id: u32,
    is_ok: bool,    
}

impl A {
    fn new(id: u32) -> Self {
        Self {
            id,
            is_ok: false,
        }
    }
}

fn main() {
    let ar = Arc::new(Mutex::new(A::new(1)));
    
    // match (a = &ar.lock().unwrap(); a.is_ok) {
    match ar.lock().unwrap().is_ok {
        true => {},
        false => println!("{}", ar.lock().unwrap().id),
        // false => println!("{}", a.id),
    };
}

Solution

  • A better way to handle this is via if let statement like below

    if let Ok(a) = ar.lock() {
        match a.is_ok {
            true => {},
            false => println!("{}", a.id),
        }
    };