# "Irrefutable Pattern" Warnings in Let Chains

**URL:** <https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238>\
**Category:** language design\
**Created:** [August 22, 2022, 1:39pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238 "2022-08-22T13:39:48Z")\
**Posts on this page:** 20\
**Page:** 2

<div class="post-metadata">

**Author:** ![CrimsonVoid](https://avatars.discourse-cdn.com/v4/letter/c/cab0a1/32.png) [@CrimsonVoid](https://internals.rust-lang.org/u/CrimsonVoid)\
**Post date:** [August 25, 2022, 2:50am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/21 "2022-08-25T02:50:32Z")

</div>

I’m not sure if C++’s comma operator is what I am looking for; I'm not super interested in generalizing this syntax for expressions outside if blocks (but I could be convinced otherwise) or _discarding_ the first/nth return value.

I find it strange that you say this is abusing a feature (which admittedly I have been known to do in the past so it’s not out of the realm of possibility) and at the same time consider `if (setup; test)` reasonable? In my mind this reads almost the same as `if let _ = setup && test` and is more flexible than languages that only allow one setup statement. If you didn’t use && you could drop the `let _` altogether and write `if setup, test` and still declare bindings when you need to `if let Ok(a) = setup, test || a.check()`

Different question, if not sequencing, how do you view let chains and what problem are they trying to solve for you? Can “chains” exist without the “let’s” or is it “let-chains” for you? Why do bindings have to be refutable (i.e. `if let hash` from @Nemo157's comment seems reasonable to me, even if you were to say `if let _` is in poor style)? (Sorry for the barrage of questions)

> **misc thoughts & opinions 🛸**
>
> At this point, I kinda want to ask if `&&` is still a good choice for let chains? The more I think about it, the more I would rather get rid of `&&` for let chains because, ya, the lint is helpful for other cases, just not universally in chains, and I can't think of a reason to prefer `&&` over `,`
> 
> * * *
> 
> > if do rx.read\_exact(); test {
> 
> I’m having a hard time trying to figure out why you need the `do` keyword here? It seems like it should be unambiguous without any additional syntax?
> 
> > write some interesting code
> 
> that _is_ some interesting code, i'll have to remember it for later haha
> 
> > use `()` equality, and drop the let binding
> 
> I guess that's not the _worst_ thing considering the alternative is universally allowing irrefutable\_let\_patterns, which I don't really want to do. I hate how it looks though lol. maybe i'll just macro it 😔

---

<div class="post-metadata">

**Author:** ![jkugelman](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jkugelman/32/8572_2.png) [@jkugelman](https://internals.rust-lang.org/u/jkugelman)\
**Post date:** [August 25, 2022, 3:05am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/22 "2022-08-25T03:05:26Z")

</div>

What do you think of this suggestion, the best one from CAD97's post?

> [@CAD97](#):
>
> ```rust
> if { rx.read_exact(&mut buf).await?; buf != info_hash } {
> // code...
> }
> 
> ```

Doesn't that do what you want without the unnecessary `let`, and without the `&&` you dislike?

---

<div class="post-metadata">

**Author:** ![CrimsonVoid](https://avatars.discourse-cdn.com/v4/letter/c/cab0a1/32.png) [@CrimsonVoid](https://internals.rust-lang.org/u/CrimsonVoid)\
**Post date:** [August 25, 2022, 3:13am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/23 "2022-08-25T03:13:06Z")

</div>

even if rustfmt formatted that correctly, it feels a little unsatisfactory considering let chains are so close to addressing this well. it's not that i dislike `&&` (well kinda, it's complicated lol), it just happens to get in the way for this use case.

---

<div class="post-metadata">

**Author:** ![toc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/toc/32/6692_2.png) [@toc](https://internals.rust-lang.org/u/toc)\
**Post date:** [August 25, 2022, 3:18am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/24 "2022-08-25T03:18:57Z")

</div>

> [@CrimsonVoid](#):
>
> Different question, if not sequencing, how do you view let chains and what problem are they trying to solve for you?

Prior to let chains rust allowed this code

```rust
if let Ok(a) = try_something() {
    ...
} else {
    return ErrSomethingFailed {};
}

```

but with some consistency this led to code like

```rust
if let Ok(a) = try_something() {
    if let Ok(b) = try_something_else() {
        if a.is_cool() && b.isnt_that_bad() {
            ...
        }
    } else {
        return ErrSomethingFailed {};
    }
} else {
    return ErrSomethingFailed {};
}

```

And okay you can use a match and you can do some other things. Between let-chains and let-else you get some significant ergonomics and the fact is that if you taught me all of the rest of rust and then told me that

```rust
if let Ok(a) = try_something() && let Ok(b) = try_something_else() { ... }

```

doesn't work I would be a little bit confused. Definitely the motivation sections of [let-else](https://rust-lang.github.io/rfcs/3137-let-else.html#motivation) and [if-let-chains](https://rust-lang.github.io/rfcs/2497-if-let-chains.html#motivation) have some well thought out answers to some of your questions.

> [@CrimsonVoid](#):
>
> Why do bindings have to be refutable (i.e. `if let hash` from @Nemo157's comment seems reasonable to me, even if you were to say `if let _` is in poor style)?

To put on my opinionated hat, `if` tests a _condition_, and runs code based on that condition. `if` communicates to the computer, and more importantly to readers of my code, the block that follows is _conditional_, it might run, it might not, based on the outcome of a test.

When I write `if A && B` I am communicating that `A` might be true, it might be false, `B` might be true, it might be false, and only if both are true will I run the code block. In your code sample, the code communicates a lie O\_O It turns out that `A` is always true, and we really only want to test `B`, and in context conveniently that means `&&` works the same as `;`.

But rust actually already has `;`, so just use that.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [August 25, 2022, 7:28am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/25 "2022-08-25T07:28:32Z")

</div>

> [@CrimsonVoid](#):
>
> Because I consider read() to be a precondition for the boolean expression. Splitting it out would be separating one conceptually grouped concept into two separate statements which hurts readability IMO.

What you have is:

1. an action with side effects (reading from a source, and filling a buffer)
2. a condition that checks the outcome of that action
3. some conditional code that depends on that condition

This seems perfectly expressed by the most straightforward code:

```rust
action();
if condition() {
    conditional_code();
}

```

You say that the condition is closely related to the preceding action -- but that is almost always true! That is already expressed by doing the action right before checking the condition -- consecutive statements in code are typically related.

You can cram the `action()` behind the `if`:

```rust
if {
    action();
    condition()
} {
    conditional_code();
}

```

but I fail to see any benefits of doing that.

You still have two expressions separated by `;`. The differences are:

- The `if` keyword has moved to a different location. The new location makes less sense because it's further away from the condition. It makes it harder to understand what exactly the actual condition being tested is.

- `action()` is now indented. This makes it harder to understand that `action()` is done unconditionally and that it has side effects that persist after the whole `if` statement.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [August 25, 2022, 8:16am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/26 "2022-08-25T08:16:13Z")

</div>

> [@jkugelman](#):
>
> What do you think of this suggestion, the best one from CAD97's post?
> 
> > [@CAD97](#):
> >
> > ```rust
> > if { rx.read_exact(&mut buf).await?; buf != info_hash } {
> > // code...
> > }
> > 
> > ```
> 
> Doesn't that do what you want without the unnecessary `let`, and without the `&&` you dislike?

How about this:

```rust
rx.read_exact(&mut buf).await?; if buf != info_hash {
    code()
}

```

This doesn't require extra braces!

---

<div class="post-metadata">

**Author:** ![SkiFire13](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/skifire13/32/7579_2.png) [@SkiFire13](https://internals.rust-lang.org/u/SkiFire13)\
**Post date:** [August 25, 2022, 8:48am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/27 "2022-08-25T08:48:17Z")

</div>

What about a situation like:

```rust
if
    let Ok(a) = something() &&
    let b = some_function(a) &&
    some_condition(&b) &&
    some_other_condition(&b)
{
    /* ... */
} else {
    /* ... */
}

```

You can't inline the `let b = some_function(a)` because it's used in two conditions, and extracting it into an additional binding introduces a new nesting level which `if-let-chains` aimed to avoid.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [August 25, 2022, 8:53am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/28 "2022-08-25T08:53:21Z")

</div>

There is no warning for this case. It only triggers if the irrefutable pattern is the first thing or the last thing in the chain.

---

<div class="post-metadata">

**Author:** ![josh](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/josh/32/5934_2.png) [@josh](https://internals.rust-lang.org/u/josh)\
**Post date:** [August 25, 2022, 12:45pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/29 "2022-08-25T12:45:30Z")

</div>

I'm glad to hear that detail got implemented; I remember we talked about it when considering let-chains, and several of us felt that being able to bind something in the _middle_ of a let-chain was important, for this exact reason (you can't pull it before the conditional because another condition comes before it, and you should be able to name expressions for simplification or repeated use).

---

<div class="post-metadata">

**Author:** ![CrimsonVoid](https://avatars.discourse-cdn.com/v4/letter/c/cab0a1/32.png) [@CrimsonVoid](https://internals.rust-lang.org/u/CrimsonVoid)\
**Post date:** [August 25, 2022, 2:06pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/30 "2022-08-25T14:06:45Z")

</div>

> if { setup; test } and all small variations

i feel like your're all getting hung up on the fact that this _specific_ example discards its return value and not what this feature actually is.

`fn setup() -> &mut T; if let borrow = setup(); test`

consider why you might want to drop mutable references as quickly as possible givens rusts sharing rules. what about Guards, Handles, or other scoped temporaries?

> if let Ok(a) = try\_something() && let Ok(b) = try\_something\_else()

you're using the feature as it is to defend itself. if the rfc proposed `;` your example would be exactly the same except `s/&&/;`. i'm not sure why let-else is relevant here? can you elaborate?

---

<div class="post-metadata">

**Author:** ![toc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/toc/32/6692_2.png) [@toc](https://internals.rust-lang.org/u/toc)\
**Post date:** [August 25, 2022, 2:23pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/31 "2022-08-25T14:23:08Z")

</div>

> [@CrimsonVoid](#):
>
> > if let Ok(a) = try\_something() && let Ok(b) = try\_something\_else()
> 
> you're using the feature as it is to defend itself. if the rfc proposed `;` your example would be exactly the same except `s/&&/;`. i'm not sure why let-else is relevant here? can you elaborate?

Of course. This example conditionally runs a block of code when `matches!(Ok(_), try_something()) && matches!(Ok(_), try_something_else())` _and_ it won't `try_something_else()` if that first part of the test fails _and_ it introduces bindings. So the semantics are quite aligned with `&&` and quite different from `;`.

---

<div class="post-metadata">

**Author:** ![ekuber](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ekuber/32/1646_2.png) [@ekuber](https://internals.rust-lang.org/u/ekuber)\
**Post date:** [August 25, 2022, 3:10pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/32 "2022-08-25T15:10:03Z")

</div>

> [@josh](#):
>
> and several of us felt that being able to bind something in the _middle_ of a let-chain was important

That style is used a lot in `rustc`.

---

<div class="post-metadata">

**Author:** ![CrimsonVoid](https://avatars.discourse-cdn.com/v4/letter/c/cab0a1/32.png) [@CrimsonVoid](https://internals.rust-lang.org/u/CrimsonVoid)\
**Post date:** [August 25, 2022, 3:16pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/33 "2022-08-25T15:16:53Z")

</div>

i asked why let-else is relevant. you explained why `s/&&/;` isn't the same. fine w/e, use `,` and define the semantics you want; that's not the point.

saying semantics are aligned with && when && has literally only been used with boolean operands (not truthy exprs) is a little absurd

why are people so intent on not wanting to support `if setup, test`. is it really worth keeping some kind of cutesy symmetry with &&

---

<div class="post-metadata">

**Author:** ![Nokel81](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nokel81/32/3966_2.png) [@Nokel81](https://internals.rust-lang.org/u/Nokel81)\
**Post date:** [August 25, 2022, 3:19pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/34 "2022-08-25T15:19:19Z")

</div>

Because `if setup, test {` is already supported in the form of `if { setup; test } {`.

---

<div class="post-metadata">

**Author:** ![CrimsonVoid](https://avatars.discourse-cdn.com/v4/letter/c/cab0a1/32.png) [@CrimsonVoid](https://internals.rust-lang.org/u/CrimsonVoid)\
**Post date:** [August 25, 2022, 3:24pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/35 "2022-08-25T15:24:41Z")

</div>

and again you've circled back to the _specific_ example that discards its return value. can you please take a minute reading before replying. even if so, why do you want to restrict how you can use this?

---

<div class="post-metadata">

**Author:** ![toc](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/toc/32/6692_2.png) [@toc](https://internals.rust-lang.org/u/toc)\
**Post date:** [August 25, 2022, 3:35pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/36 "2022-08-25T15:35:03Z")

</div>

> [@CrimsonVoid](#):
>
> i asked why let-else is relevant.

Some of the design decisions behind if-let-chains and let-else are interrelated, this is discussed mostly in the let-else RFC. They both solve generally the same problem (ergonomics around conditional `let`).

> [@CrimsonVoid](#):
>
> saying semantics are aligned with && when && has literally only been used with boolean operands (not truthy exprs) is a little absurd

There is some additional discussion about wanting to leave the door open for `let X(_) = ...` to be treated as an _expression_ returning a boolean, or at least to mimic those semantics. The syntax was purposefully geared towards making this a natural analogy; in any case the motivation and justification and even some counterarguments are in the RFCs, as well there are some discussion threads for the pre-RFCs. Which is all a lot to read I know but it's also a lot to retread.

---

<div class="post-metadata">

**Author:** ![Nokel81](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/nokel81/32/3966_2.png) [@Nokel81](https://internals.rust-lang.org/u/Nokel81)\
**Post date:** [August 25, 2022, 4:24pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/37 "2022-08-25T16:24:08Z")

</div>

Then what do you want those semantics to mean? The comma operator in c/c++ does just discard the result of `setup`. If you want to use the result itself then you can just bind it in a block.

I guess I can sort of envision a case where you would want to bind a value to a name (unconditionally) and then continue the if chain also with patterns (of the form `&& let Some(inner) = get_maybe() ...`. If that is what you are talking about then sure this lint might be annoying. But it also isn't wrong and having it above the `if` in a block of its own isn't that bad either.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [August 25, 2022, 6:25pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/38 "2022-08-25T18:25:22Z")

</div>

> [@Nokel81](#):
>
> But it also isn't wrong and having it above the `if` in a block of its own isn't that bad either.

I think I've figured out the case which might actually be a false positive. (Saying "don't fixate on the previous example where the result is discarded and not providing an _ **obvious** _ new example is problematic because people _will_ prefer discussing an example over a missable theoretical. Plus, asynchronous communication and all that means people aren't always replying just to the most recent thread status.)

Consider:

```rust
if let handle = mutex.lock().unwrap()
&& handle.test() {
    // do things with handle
}

// do things where the lock must be released

```

(Note that the unwrap here is _desired_, to propagate the panic that poisoned the mutex. Using `if let Ok` would be incorrect.)

This is potentially subtle because of drop order. The equivalent without the irrefutable `if let` would have to be

```rust
let handle = mutex.lock().unwrap();
if handle.test() {
    // do things with handle
}
drop(handle); // !important

// do things where the lock must be released

```

in order to drop the handle, or introduce an extra block, e.g.

```rust
{
    let handle = mutex.lock().unwrap();
    if handle.test() {
        // do things with handle
    }
}

// do things where the lock must be released

```

Note however that this _isn't_ a problem if `handle` were some `&mut` (as in what might be your new example that you wanted people to consider? it is very unclear since the example was not spelled out well) as the lifetime `&mut` can be terminated early ("non lexical lifetimes"). The end-scope drop timing is only relevant for types which have drop glue (`impl` or transitively contain something which `impl Drop`).

So considering this example, I do think it might be reasonable to relax the irrefutable binding lint for the case where

- the value is bound; and
- the value's type has a semantic drop.

Thus

- `if let _ = setup() && test` is linted against as an unbound irrefutable `if let` pattern, with a suggestion to move `setup()` before the `if`.
- `if let v = setup() && test` where `v` is a reference is linted against as an irrefutable `if let` pattern, with a suggestion to move `let v = setup();` before the `if`.
- `if let v = setup() && test` where `v` has drop glue but is not used is linted against as an unused binding, with a suggestion to use or rename as `_v`.
- `if let v = setup() && test` where `v` has drop glue and is used is not linted against.

This applies equally to any irrefutable pattern with a binding. Two additional clarifying notes:

- If all patterns in an `if let` chain are irrefutable and no boolean tests exist, lint; it is better to just use a normal block and `let`s inside the block.
- An unchained `if let` satisfies the "all" clause above, so this change only impacts unstable code.

I do think it's still potentially misleading in that the assignment cannot fail, but the drop order benefits are stronger when they are relevant IMHO.

---

<div class="post-metadata">

**Author:** ![tczajka](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tczajka/32/8923_2.png) [@tczajka](https://internals.rust-lang.org/u/tczajka)\
**Post date:** [August 26, 2022, 7:33am UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/40 "2022-08-26T07:33:50Z")

</div>

> [@CAD97](#):
>
> So considering this example, I do think it might be reasonable to relax the irrefutable binding lint for the case where
> 
> - the value is bound; and
> - the value's type has a semantic drop.

I agree that the warning should be relaxed in some cases, especially since irrefutable patterns already are an accepted style in the **middle** of a let chain.

I think it should be relaxed for all cases when the **first** `let` in the chain (but not the last `let` in the chain) binds a variable, regardless of whether there is drop glue on its type.

Scoping a variable locally is convenient regardless of whether or not there is drop glue. It would be confusing if the warning allowed it for some types and not for others.

Example:

```rust
if let potential_answer = calculate() &&
        valid_answer(&potential_answer) {
    return potential_answer;
}

```

With your proposal, this would be a lint for `i32` but not for `Vec<i32>`. I think if the lint is relaxed, it should be relaxed in this case for all types.

The alternative is to either keep `potential_answer` in scope longer than necessary, or use extra braces, similarly to your `handle` example:

```rust
{
    let potential_answer = calculate();
    if valid_answer(&potential_answer) {
        return potential_answer;
    }
}

```

> [@CAD97](#):
>
> If all patterns in an `if let` chain are irrefutable and no boolean tests exist, lint; it is better to just use a normal block and `let`s inside the block.

This is already covered by the warning on the **last** `let` in the chain being irrefutable. That never makes sense, and shouldn't be relaxed.

---

<div class="post-metadata">

**Author:** ![zackw](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/zackw/32/2071_2.png) [@zackw](https://internals.rust-lang.org/u/zackw)\
**Post date:** [August 26, 2022, 8:37pm UTC](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/41 "2022-08-26T20:37:59Z")

</div>

> [@Nemo157](#):
>
> > [@zackw](#):
> >
> > ```rust
> > if let hash = rx.read_exact(&mut buf).await? && hash != info_hash {
> > // do something here that uses `hash`
> > }
> > 
> > ```
> 
> This would hit the same lint

I see. I misunderstood what the lint is about -- I thought it was specifically about `if let _ = ... && ...`, i.e. discarding the result of the left-hand side of the &&, in which case why not write a plain `if`?

I'm in agreement with @tczajka ([comment 40](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238/40)) that the warning should be relaxed for an irrefutable _first_ `let` in a conditional chain, whenever it binds a name (as it already is in the middle of a chain).

[Previous page](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238.md?page=1)

[Next page](https://internals.rust-lang.org/t/irrefutable-pattern-warnings-in-let-chains/17238.md?page=3)
