return
The return statement exits a function, optionally with a value.
Surface Syntax#
Return a value:
return <expr>;
Return from a void function:
return;
Semantics#
When a return statement executes:
- the current function terminates immediately, and
- control transfers back to the caller,
- carrying a return value if the function’s result type is non-
void.
No statements after a return in the same control-flow path are executed.
Type Checking Rules#
The checker enforces:
returnis only valid inside a function body (otherwiseE2009).- In a function with non-
voidresult typeR,returnmust provide an expression whose type isR(otherwiseE2009). - In a
voidfunction,return;is permitted andreturn <expr>;is rejected (E2009). - In a function with non-
voidresult, falling off the end of the function body is a compile-time error (diagnostics,E2010).
Examples#
Returning from main#
fn main () -> int {
return 0;
}
Early return#
fn main () -> int {
let x: int = 1;
if x == 0 {
return 0;
}
return 1;
}
return; in a void function#
struct Counter {
value: int,
}
impl Counter {
fn inc (mut self: &Counter) -> void {
self.value += 1;
return;
}
}
Notes#
Supported forms:
return <expr>;from non-voidfunctions, with type checking.return;fromvoidfunctions.- Missing return in a non-
voidfunction is rejected (E2010).
examples:
Source repository · Edit this page · View Markdown