Skip to content

← Shape Your Data: Structs, Enums, Pattern Matching step 16 of 26

Medium Primitives

Combine pattern matches with let-chains

pub fn best_pair(a: Vec<i64>, b: Vec<i64>, limit: i64) -> Option<i64>

Pair values at the same index in a and b. Among pair sums that are at most limit, return the largest as Some(sum). Return None if no pair qualifies. Use a let-chain to combine the two lookups and the limit check.

Ignore unmatched elements in the longer list. Either empty list means there are no pairs. Negative values and negative limits are allowed, so do not use zero as the initial best sum. Assume every paired addition fits in i64; this exercise does not define wrapping or saturating overflow behavior.

For a = [1, 2, 3], b = [10, 20, 30] and limit = 25, the sums are 11, 22 and 33. Only the first two qualify, so return Some(22). For a = [5, -5], b = [5, -5] and limit = 0, return Some(-10). The harness represents Some(n) as a JSON number and None as null.

Combine dependent conditions

The starter checks the conditions with nested blocks:

if let Some(x) = a.get(i) {
    if let Some(y) = b.get(i) {
        if x + y <= limit {
            // Update the best qualifying sum.
        }
    }
}

A let-chain expresses the same checks in one condition:

if let Some(x) = a.get(i)
    && let Some(y) = b.get(i)
    && x + y <= limit
{
    // Update the best qualifying sum.
}

The checks run left to right and short-circuit. If the first lookup returns None, the later conditions are skipped. If both lookups succeed, x and y are references to the paired values and can be used in the final condition and body. Their bindings are not available in an else branch.

Keep best as an Option<i64>: the first qualifying sum changes None to Some(sum), and later qualifying sums replace it only when larger. A limit comparison is inclusive, so a sum equal to limit qualifies.

Edition and lint behavior

Let-chains became stable in Rust 1.88 and require edition 2024 or later. This harness uses edition 2024. They work in if and while conditions, combining pattern matches and boolean checks with &&; || is not supported between let-chain clauses. See the edition guide.

The supplied nested starter can compute the requested result, but Clippy's collapsible_if lint flags its nesting under this toolchain. With warnings denied, it must be rewritten. This is a lint check on the supplied code, not a claim that nested conditions are invalid Rust or that every alternative implementation must use a let-chain.

Edition 2024 also shortens some if let temporary lifetimes: on a failed pattern match, affected temporaries are dropped before entering else, rather than after the whole expression. On a successful match they live through the consequent block. This matters for guards with destructors; the borrowed integer lookups here do not need such cleanup. See the temporary-scope guide.