Why do I have to use "return" when I use only "if" but I don't need to use it when it is accompanied by "else"?
These codes work as they should and compile.
fn sum_if(x: u32, y: u32, cond: bool) -> u32 {
if cond {
x + y
}
else {
0
}
}
fn sum_if(x: u32, y: u32, cond: bool) -> u32 {
if cond {
return x + y
}
else {
return 0
}
}
These codes don't work as they should and compile.
fn sum_if(x: u32, y: u32, cond: bool) -> u32 {
if cond {
x + y;
}
0
}
These code does not compile but follows the case of the first code without "return" and the error message is not very useful.
fn sum_if(x: u32, y: u32, cond: bool) -> u32 {
if cond {
x + y
}
0
}
error[E0308]: mismatched types
--> source_file.rs:6:5
|
6 | x + y
| ^^^^^ expected (), found u32
|
= note: expected type `()`
found type `u32`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
Why in the last code it is not possible to use the if without return and inside and outside the if there are outputs for the function? Wouldn't that be language inconsistency?
Please don't attack me, it's just a question that hasn't left my head for a few days