if-let Expression
The if-let
expression first evaluates the expression on the right of <-
in the condition. If the value matches the pattern on the left of <-
, the if
branch is executed. Otherwise, the else
branch is executed (which can be omitted). Example:
main() {
let result = Option<Int64>.Some(2023)
if (let Some(value) <- result) {
println("Operation successful, return value: ${value}")
} else {
println("Operation failed")
}
}
Run the preceding program and the following information will be displayed:
Operation successful, return value: 2023
In the above program, if the initial value of result
is changed to Option<Int64>.None
, the if-let
pattern matching will fail, and the else
branch will be executed.
main() {
let result = Option<Int64>.None
if (let Some(value) <- result) {
println("Operation successful, return value: ${value}")
} else {
println("Operation failed")
}
}
Run the preceding program and the following information will be displayed:
Operation failed