if
Source: compiler/src/builtin_docs/keywords.md Runs a block when a bool condition is true.
The condition needs no parentheses and the body always takes braces. Chain
alternatives with else if and else. if let Pattern = value { … } runs the
block when the value matches the pattern, binding its names.
fn sign(int n) -> int {
if n < 0 {
return -1;
} else if n == 0 {
return 0;
} else {
return 1;
}
}
fn main() {
let found = Option::Some(3);
if let Option::Some(v) = found {
let doubled = v * 2;
}
}
See also#
boolfn: 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.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.