Return Expressions
The widget
function in the last example
looked like this:
fn widget() -> i32 {
3 + 6
}
I bring that up to point out that there isn't
a ;
after the 3 + 6
. This is different
from all the other lines we've seen
in functions so far.
There are three reasons for this:
- Rust functions return the last expression at the end of their code block
- The
;
ends expressions. - Rust has a default return type that we'll discuss on the next page.
What all that means is if we did this:
3 + 6;
instead of:
3 + 6
we'd be end the expression that did
the addition. That expression is
what provides the i32
value that the
function is setup to return based off
its definition. So, we'd end up with an
error.
Run the code again with the ;
in place
to see what the error looks like and we'll
talk about it on the next page.
SOURCE CODE
fn main() {
let alfa = widget();
println!("alfa is {}", alfa);
}
fn widget() -> i32 {
3 + 6;
}