Chained if statements in rust?

Viewed 145

The Swift language supports multiple if statements on one line.

import Foundation

let x: Int? = 7

if let y = x, pow(Double(y), 2) == 49 {
    // do something
}

In rust I need to do

let x: Option<i32> = Some(7);
if let Some(y) = x {
    if y.pow(2) == 49 {
        // do something
    }
}

Is there a way to do something like the Swift solution in rust?

1 Answers

You can map the operation before, and then match it fully:

if matches!(x.map(|y| y.pow(2)), Some(49)) {
    println!("Yeah");
}

Or using ==:

if x.map(|y| y.pow(2)) ==  Some(49) {
    println!("Yeah");
}

Playground

Related