From 871aedbcdf2d25cf6519c7495a3866c1be405447 Mon Sep 17 00:00:00 2001 From: est31 Date: Mon, 25 Nov 2024 07:38:11 +0100 Subject: [PATCH] Document if/while let chains --- src/SUMMARY.md | 1 + src/rust-2024/let-chains.md | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 src/rust-2024/let-chains.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index c4e8476..74a1c24 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -42,6 +42,7 @@ - [Language](rust-2024/language.md) - [RPIT lifetime capture rules](rust-2024/rpit-lifetime-capture.md) - [`if let` temporary scope](rust-2024/temporary-if-let-scope.md) + - [`let` chains in `if` and `while`](rust-2024/let-chains.md) - [Tail expression temporary scope](rust-2024/temporary-tail-expr-scope.md) - [Match ergonomics](rust-2024/match-ergonomics.md) - [Unsafe `extern` blocks](rust-2024/unsafe-extern.md) diff --git a/src/rust-2024/let-chains.md b/src/rust-2024/let-chains.md new file mode 100644 index 0000000..75256c0 --- /dev/null +++ b/src/rust-2024/let-chains.md @@ -0,0 +1,37 @@ +# `let` chains in `if` and `while` + +## Summary + +- Allow chaining of `let` expressions in the condition operand of `if` and `while`. + +## Details + +Starting with the 2024 Edition, it is now allowed to have chaining of `let` expressions inside `if` and `while` condition operands, +where chaining refers to `&&` chains. The `let` expressions still have to appear at the top level, +so `if (let Some(hi) = foo || let Some(hi) = bar)` is not allowed. + +Before 2024, the `let` had to appear directly after the `if` or `while`, forming a `if let` or `while let` special variant. +Now, `if` and `while` allow chains of one or more `let` expressions, possibly mixed with expressions that are `bool` typed. + + +```rust +fn sum_first_two(nums: &[u8]) -> Option { + let mut iter = nums.iter(); + if let Some(first) = iter.next() + && let Some(second) = iter.next() + { + first.checked_add(second) + } else { + None + } +} +``` + +The feature is edition gated due to requiring [if let rescoping], which is a Edition 2024 change. + +## Migration + +The switch to Edition 2024 doesn't neccessitate any migrations due to this feature, +as it creates a true extension of the set of allowed Rust programs. + +[if let rescoping]: temporary-if-let-scope.html