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~
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};
Saad-py:
why does this not work
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 @Cerber-Ursi 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
H2CO3
March 3, 2021, 8:32am
8
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:
Snake Case go brrrrrrr
Variable names add _ to beginning
Unused variables go Brrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
1 Like
system
Closed
June 1, 2021, 11:44am
12
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.