Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If let binding with boolean expression

Tags:

rust

This has probably been asked before but I couldn't find anything..

In Go, you are able to do something like this

v1 := 3
v2 := 4

if v := v1 - v2; v < 4 {
   // use v 
} 

In rust, I couldn't find a way to do it with if let bindings

let v1 = 3;
let v2 = 4;

// able to match an exact value
if let v @ 4 = v1 - v2 {}

// but unable to match a range of value like in a `match` block
if let v @ (0..4) = v1 - v2 {} 
if let v (if v < 4) = v1 - v2 {}

Of course declaring v outside works but is kind of awkward since it is only used in the if block

like image 735
Midnight Exigent Avatar asked Mar 20 '26 01:03

Midnight Exigent


2 Answers

Responding to this

Of course declaring v outside works but is kind of awkward since it is only used in the if block

In Rust, you can create explicit blocks whenever you like. Consider

// Some code ...
{
  let v = v1 - v2;
  if v < 4 {
    ...
  }
}
// Some more code ... (v doesn't exist down here anymore)

If your concern is local variables having too large of a scope (which is a fair concern), then you can create an explicit block to denote when the scope should end, to make it clear to both the borrow checker and the human reader that the variable is not used beyond that point.

like image 170
Silvio Mayolo Avatar answered Mar 22 '26 19:03

Silvio Mayolo


Your first attempt is fine, it's just that exclusive range patterns (..) are experimental. You can use inclusive patterns (..=) instead:

if let v @ 0..=3 = v1 - v2 {}

Guards (if ...) are not available for if let, but you can use match:

match v1 - v2 {
    v if v < 4 => {}
    _ => {}
}
like image 38
Chayim Friedman Avatar answered Mar 22 '26 19:03

Chayim Friedman



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!