defer
Source: compiler/src/builtin_docs/keywords.md Schedules a block to run when the enclosing function exits.
Deferred blocks run on every return, on falling off the end, and while a
panic or task cancellation unwinds, in reverse order of the defer
statements that were reached. The block sees outer locals only when they
are listed in defer use (…).
fn work(Vec<string> log) -> int {
log.push("start");
defer use (log) {
log.push("cleanup");
}
return log.len(); // 1: the defer runs after the value is computed
}
fn main() {
let log: Vec<string> = Vec::new();
let n = work(log); // log is now ["start", "cleanup"]
}
See also#
fn: Declares a function, a method, or (written in an expression) an anonymous function.let: Declares a mutable local variable.const: Declares a binding that cannot be reassigned: a local, a module constant, or a class field that is set only bynew.static: Declares a module-level or class-level slot shared by the whole program, or a method withoutself.readonly: A read-only view of a value: nothing reachable through it can be changed.if: Runs a block when aboolcondition is true.else: Introduces the branch of anifthat runs when its condition is false (or its pattern does not match).while: Repeats a block while aboolcondition is true.