Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chained if statements in rust?

Tags:

rust

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?

like image 450
noatbfgtxa Avatar asked Mar 29 '26 16:03

noatbfgtxa


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

like image 130
Netwave Avatar answered Mar 31 '26 04:03

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!