by 0942v8653 · 11y ago · 0 comments
(I really like Rust's take on this with the semicolons—just leave off the semicolon to return—it makes the semicolon actually useful.)
fn foo(x: bool) -> i32 {
if x {
1 // no semicolon on the 1
}
let a = 2 + 3;
return a * 4;
}
It's not implicitly returning the 1 from `foo`. An early return would need to be written `if x { return 1 }`. On the other hand, the `return a * 4;` could just be written `a * 4` since it's at the end of the function.This rule means the scanning required is just looking at the end of the function.
In any case, having a static type system means I have never personally encountered a bug caused by this sort of implicit return in Rust.
Maybe I'll add a 'noreturn' keyword; single expresions are automatically returned, and you can use a 'noreturn' statement to explicitly return void despite running a non-void expression.
Something I've played with in languages I've worked on is named returns [1], which I like for that case.
[1] https://github.com/stormbrew/channel9/blob/master/sample/c9s... -- see the get function definition, '-> return' names the return 'channel' and 'return <- val' calls it (which returns). Now I might consider having an implicit '<- val' with no lhs that calls the current function's return, I think.
I do think a special case for single statements makes sense, though.
Why aren't declaration statements in Rust just expressions that evaluate to the value being bound to the name being declared?
Would this mess up Rust's type checker somehow?
If it's not the norm, I'd rather have an explicit "nil" or something at the end.