Can be 'if' on the left side in Rust?

⚓ Rust    📅 2026-06-24    👤 surdeus    👁️ 4      

surdeus

Usually I use 'if' on the right side of expressions, for example:

let exp = if some_cont {c} else {d};

It works great, but sometimes you need something different, for example:

trait Oper {
    fn plus(&mut self, val: i32);
    fn minus(&mut self, val: i32);
}
struct Val {
    it: i32,
}

impl Oper for Val {
    fn plus(&mut self, val: i32) {
        self.it += val
    }
    fn minus(&mut self, val: i32) {
        self.it -= val
    }
}
fn main() {
    let mut v = Val { it: 4 };
    let cond = 7;
    v. if cond < 5 {plus(5)} else {minus(3)};
    println!("result {}", v.it)
}

I want to select a called function by a condition, but Rust tells:

error: expected identifier, found keyword `if`
  --> /media/exhdd/Dev/modu/oper/oper.rs:20:8
   |
20 |     v. if cond < 5 {plus(5)} else {minus(3)};
   |        ^^ expected identifier, found keyword

error: expected one of `(`, `.`, `::`, `;`, `?`, `}`, or an operator, found `cond`
  --> /media/exhdd/Dev/modu/oper/oper.rs:20:11
   |
20 |     v. if cond < 5 {plus(5)} else {minus(3)};
   |           ^^^^ expected one of 7 possible tokens

error: aborting due to 2 previous errors

You may say - why is it so strange request?, it can be done like:

trait Oper {
    fn plus(&mut self, val: i32);
    fn minus(&mut self, val: i32);
}
struct Val {
    it: i32,
}

impl Oper for Val {
    fn plus(&mut self, val: i32) {
        self.it += val
    }
    fn minus(&mut self, val: i32) {
        self.it -= val
    }
}
fn main() {
    let mut v = Val { it: 4 };
    let cond = 7;
    if cond < 5 {
        v.plus(5)
    } else {
        v.minus(3)
    };
    println!("result {}", v.it)
}

But sometimes, v is calculated by a quite complex expression and I do not want to duplicate it in both branches if the 'if'. What are my other options in the case? Calculate v, store it and then apply 'if', right?

7 posts - 5 participants

Read full topic

🏷️ Rust_feed