I’m new to Rust and I’m trying to write down a simple example using loops
the code is the following:
fn main() {
let exit: u8 = loop_break(20, 5);
println!("loop_break exited with value {exit}");
let exit: u8 = loop_break(20, 35);
println!("loop_break exited with value {exit}");
let exit: u8 = loop_break(20, 20);
println!("loop_break exited with value {exit}");
}
fn loop_break(cycles: u8, exit: u8) -> u8 {
if exit > cycles {
cycles
}
let mut _i:u8 = 0;
loop {
if _i == exit {
break exit - 1;
}
_i += 1;
}
return _i;
}
When I try to compile it the compiler gives me this error message that I can understand
error[E0308]: mismatched types
--> src/main.rs:23:9
|
22 | / if exit > cycles {
23 | | cycles
| | ^^^^^^ expected `()`, found `u8`
24 | | }
| |_____- expected this to be `()`
|
help: you might have meant to return this value
|
23 | return cycles;
| ++++++ +
error[E0308]: mismatched types
--> src/main.rs:29:19
|
29 | break exit - 1;
| ^^^^^^^^ expected `()`, found `u8`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `flow-control` due to 2 previous errors
Why does the compiler state it expects a unit value if I defined the function as returning a u8 type?
Thank you in advance
>Solution :
if exit > cycles {
cycles
}
Rusts expects your first if
statement to return the unit type, because it does not have an else
branch. All branches/arms of conditional statements like if
or match
must return the same type and must be complete if they should return something other than the unit type. No case can be left untreated. If you omit else
, you leave all the cases where the condition of if
is false
untreated. Therefore, the compiler automatically assumes that your incomplete conditional statement must return the unit type, which is a special type in Rust indicating "nothing is returned." Think of your incomplete if
statement as syntactic sugar for:
if exit > cycles {
cycles
} else {
()
}
cycles
is u8
and ()
is of type ()
, which are not the same type. This section of the book may be of interest to you.
What you want to do here instead is what the compiler suggests. You want to return from your function early, using a return
statement:
if exit > cycles {
return cycles;
}
Read more about the difference between an expression (cycles
) and a statement (return cyclces;
) in this section of the book.