Does the return results' type of branches of if...else expression must be same?


#1

I occur a puzzle when reading the if chapter of The Rust Programming Language

fn main() {
    let x = 1;
    let y = if x == 1 { ; } else { 2 };  // error:  expected (), found integral variable
    println!("y is { :? }", y);
}

Then I try this code:

fn main() {
    let x = 1;
    let y = if x == 1 { 0 } else { 2 };
    println!("y is { :? }", y);
}

I get the right result y is 0.
So I guess that as for types in if { type_1 } and else (if) { type_2 }, type_1 must be the same as type_2. Am I right?


#2

That’s right. match arms have the same requirement.


#4

Thank you.