One line conditionals

Hi, I am new to rust and I have done python and some ruby.

First my piece of code
let va = if 2 != 3 {7} else if 2 == 2 {2};

Why cannot I do this in the compiler it gives me an error that I need parenthesis but why cannot I add an else if here.

SO in simple words my question is that how can I add else if in conditionals like these.

Thanks in Advance~ :slight_smile:

Two things:

  1. if (2 != 3) { 7 } and so on: the parens go around the condition.

  2. There must be an else, or the if must evaluate to (). Yours has an if and an else if but no final else.

Oh yes, I added an else and it worked and I will let you know the parenthesis around the condition work

Another small problem

why does this not work

let va = if (arr.len() != l) {7} else if (arr.len() == l) {2};

Because Rust will not prove that these two conditionals cover all cases. From the compiler's point of view, there are three cases: arr.len() != l, arr.len() == l, and the third one where neither is true, and you don't provide any value to va in the third case.

Ok @Cerberuser and @derspiny
Thanks for helping me out
I understand it now that parenthesis are important in some cases and an else is compulsory

These aren't necessary right? I'm fairly certain you can just so if 2 != 3.

2 Likes

No, there's no need for parentheses there. Only the curly braces are mandatory.

1 Like

Please read the pinned code formatting guide.

You don't need the parenthesis. In fact you'll get a warning if you add them unnecessarily.

Here's a couple ways to complete your examples. Incidentally, are you reading the compiler errors? They usually give advice and it is often the solution you're looking for.

1 Like

If the first conditions don't cover all cases, this will silently produce unexpected results. I'd prefer to use unreachable!() here, which will panic if the code ever reaches it:

    let va = if 2 != 3 {
        7
    } else if 2 == 2 {
        2
    } else {
        unreachable!()
    };
3 Likes

@quinedot Yeah I know the warnings:

  1. Snake Case go brrrrrrr
  2. Variable names add _ to beginning
  3. Unused variables go Brrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
1 Like