# Loop-match, for-match

**URL:** <https://internals.rust-lang.org/t/loop-match-for-match/13867>\
**Category:** language design\
**Created:** [January 18, 2021, 9:21pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867 "2021-01-18T21:21:10Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![hclarke](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hclarke/32/7642_2.png) [@hclarke](https://internals.rust-lang.org/u/hclarke)\
**Post date:** [January 18, 2021, 9:21pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/1 "2021-01-18T21:21:10Z")

</div>

this has already been discussed, but it was pre 1.0: [Pre-RFC: loop/for/else match](https://internals.rust-lang.org/t/pre-rfc-loop-for-else-match/930)

But priorities have shifted from getting a stable feature set, to making things nicer, so I think this deserves another look

the idea is to have loops like this:

```rust
loop match expr {
    Foo(x)=>{...}
    Bar(x)=>{...}
}

for match in iter_expr {
    Foo(x)=>{...}
    Bar(x)=>{...}
}

```

which would roughly desugar to:

```rust
loop {
    match expr {
        Foo(x)=>{...}
        Bar(x)=>{...}
    }
}

for item in iter_expr {
    match item {
        Foo(x)=>{...}
        Bar(x)=>{...}
    }
}

```

It'd be good for dropping a level of braces for event loops and such

the for loop syntax i'm suggesting here is definitely more awkward than loop. it'd be nice to have some consistency and allow a match to replace any block (if/else bodies, functions, while loops, etc), but i can't think of a nice syntax for those cases.

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 18, 2021, 9:43pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/2 "2021-01-18T21:43:59Z")

</div>

> [@hclarke](#):
>
> more awkward than loop. it'd be nice to have some consistency and allow a match to replace any block (if/else bodies, functions, while loops, etc), but i can't think of a nice syntax for those cases.

Well, if and while don't bind anything, so this doesn't really apply there. For functions, well, at least for single argument closures one could use something like `|match| { /* match arms */}`. This has some precedent in Haskell, I've explained it in more detail in this post in a thread that was also about eliminating extra indentation levels:

> [@Eliminating "seemingly unnecessary" braces](https://internals.rust-lang.org/t/eliminating-seemingly-unnecessary-braces/12971/30):
>
> In Haskell you would use a higher order function for a loop and there is the "lambda case" syntax extension that allows for using pattern matching and multiple branches directly in an anonymous function. This looks like for\_ myCollection \case Just x -\> {- do something with x -} Nothing -\> {- do something on Nothing -} Where Just and Nothing are the Haskell equivalent of Some and None and Iʼm also using another syntax extension "block arguments" to avoid having to write a $ before the \. E…

* * *

Thinking about it again now, one could even consider supporting e. g. `|match, match, match| { (a, b, c) => {...} }`, bundling up multiple values in a tuple.

And one could go much further and generalize this to allowing `match` as a pattern in general in some places, e. g.

```rust
while let Some(match) = foo.next() {
    0 => {
        bar1();
        bar2();
    }
    n => baz(n),
}

```

and similar for `if let` and even function definitions

```rust
fn foo(match: Option<bool>, u: char, (match, i): (i32, u8)) {
    (Some(true), 0) => bar(), 
    (None, n) if n > 0 => baz(), 
    (_, n) => qux(), 
}

```

* * *

_Edit:_ Going back to discussing your suggestions, this generalization would mean the `for` syntax stays as you proposed, and the `loop match expr { ... }` needs to be written as `while let match = expr { ... }`. _Admitted, that's a bit of a keyword zoo, and a bit too `while true`-style, so perhaps `loop match` could be a new “abbreviation” of `while let match =`._

---

<div class="post-metadata">

**Author:** ![hclarke](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hclarke/32/7642_2.png) [@hclarke](https://internals.rust-lang.org/u/hclarke)\
**Post date:** [January 18, 2021, 10:11pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/3 "2021-01-18T22:11:33Z")

</div>

> [@steffahn](#):
>
> if and while don't bind anything, so this doesn't really apply there

i was kinda thinking of something like the thread you linked. (`if <cond> match <expr> { }`) but i'm not a fan of that syntax, since it'd easily encourage either long lines or "goto fail" indentation

the single-argument lambda match (or first argument?) seem nice to me.

i think i have a strong preference for keywords to show up at the beginning of the expression, so they can't hide as easily

---

<div class="post-metadata">

**Author:** ![mbrubeck](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mbrubeck/32/174_2.png) [@mbrubeck](https://internals.rust-lang.org/u/mbrubeck)\
**Post date:** [January 18, 2021, 11:09pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/4 "2021-01-18T23:09:55Z")

</div>

Another somewhat-related proposal from a while back: [A fn match syntax sugar](https://internals.rust-lang.org/t/a-fn-match-syntax-sugar/4562)

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [January 19, 2021, 12:10am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/5 "2021-01-19T00:10:49Z")

</div>

`loop match` seems logical to me, because that's just optional braces. However, I don't write `loop` that often to appreciate a special shorthand syntax for it.

I can see `else match` or `else <keyword> {}` in general being a useful syntax sugar, and it wouldn't be too weird, because `else if` already exists in Rust, and C is even more permissive here.

However, I needed a triple double-take for `for match` and `fn match`. That's an unusual, very dense syntax. A magic variable name that changes syntax of a next block is too much for me.

---

<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:** [January 19, 2021, 8:39am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/6 "2021-01-19T08:39:23Z")

</div>

Agreed on both counts.

I do like the idea of being able to write top-level matches more easily, but this syntax feels like it optimizes for writing at the expense of reading.

---

<div class="post-metadata">

**Author:** ![dhardy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/dhardy/32/2399_2.png) [@dhardy](https://internals.rust-lang.org/u/dhardy)\
**Post date:** [January 19, 2021, 8:49am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/7 "2021-01-19T08:49:31Z")

</div>

For me one of the biggest use of `loop` is to handle the lack of a default case in a `for` loop. IMO new syntax around `for` and `loop` should first try to solve that:

```rust
'outer: loop {
    for item in list {
        if cond { break 'outer f(item); }
    }
    break default_val();
}

```

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 19, 2021, 11:00am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/8 "2021-01-19T11:00:32Z")

</div>

> [@dhardy](#):
>
> ```rust
> 'outer: loop {
> for item in list {
> if cond { break 'outer f(item); }
> }
> break default_val();
> }
> 
> ```

you mean

```rust
list.into_iter().find(|item| cond).map_or_else(default_val, f)

```

or

```rust
if let Some(item) = list.into_iter().find(|item| cond) {
    f(item)
} else {
    default_val()
}

```

?

_Edit:_ Yet another way, now that [`then`](https://doc.rust-lang.org/beta/std/primitive.bool.html#method.then "bool::then") is almost stable (already in beta):

```rust
list.into_iter()
    .find_map(|item| (cond).then(|| f(item))
    .unwrap_or_else(|| default_val())

```

or if you like blocks (and fighting against `rustfmt`)

```rust
list.into_iter().find_map(|item| {
    (cond).then(|| {
        f(item)
    })
}).unwrap_or_else(|| {
    default_val()
})

```

---

<div class="post-metadata">

**Author:** ![hclarke](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/hclarke/32/7642_2.png) [@hclarke](https://internals.rust-lang.org/u/hclarke)\
**Post date:** [January 19, 2021, 6:23pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/9 "2021-01-19T18:23:16Z")

</div>

> [@kornel](#):
>
> A magic variable name that changes syntax of a next block is too much for me

oh, i didn't parse it that way, but i can see how it'd be very easy to

i parsed it as `(for match) in expr`. like, a 2 word keyword. but it's just lowercase letters, so if you're not looking at it with syntax highlighting, it'd easily look like a variable name

maybe dropping the `for` would work better, and have `match in` be a thing?

```rust
match in iter_expr {
    Foo(x)=>{...}
    Bar(x)=>{...}
}

```

> [@kornel](#):
>
> I can see `else match` or `else <keyword> {}` in general being a useful syntax sugar, and it wouldn't be too weird, because `else if` already exists in Rust, and C is even more permissive here.

that would be useful for `Option<Enum>` and `Result<Enum>` code, which comes up often. i almost want it to handle the unwrapping, but no decent syntax is coming to mind

```rust
if x.is_none() {
  ...
}
else match x.unwrap() {
    Foo(x)=>{...}
    Bar(x)=>{...}
}

```

> [@mbrubeck](#):
>
> Another somewhat-related proposal from a while back: [A fn match syntax sugar](https://internals.rust-lang.org/t/a-fn-match-syntax-sugar/4562)

i like the match closures from there:

```rust
xs.map(match {
    Foo(x)=>{...}
    Bar(x)=>{...}
})

```

maybe less of a big deal, since you're not saving a level of indentation/braces on a closure like that

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 19, 2021, 7:08pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/10 "2021-01-19T19:08:05Z")

</div>

> [@hclarke](#):
>
> ```rust
> if x.is_none() {
> ...
> }
> else match x.unwrap() {
> Foo(x)=>{...}
> Bar(x)=>{...}
> }
> 
> ```

^^^ am I missing something or is this just a new, less readable alternative for

```rust
match x {
    None => {
        ...
    }
    Some(Foo(x)) => {...}
    Some(Bar(x)) => {...}
}

```

?

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [January 20, 2021, 9:01am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/11 "2021-01-20T09:01:54Z")

</div>

This is definitely not a case that needs "shorter syntax". A loop is a loop, a match is a match, and if you need both, you can _just_ compose them.

Composability (which is already one of Rust's strengths) is a much better alternative over adding syntax for every possible combination of control structures. It's clearer and easier to learn/teach as well as easier to change.

If you have too much indentation in your code, the solution is not to incoherently lump together unrelated parts of it. The solution is to refactor and modularize. Too clever and dense code won't become higher-quality due to more syntactic sugar and cleverness (arguably, that only makes it worse). It becomes higher-quality due to design effort put into it being higher-quality.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [January 20, 2021, 7:28pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/12 "2021-01-20T19:28:09Z")

</div>

Unfortunately neither of the syntax you proposed to simplify `'outer: loop { for ... { if ... { break 'outer ...; }; break ...; }` works _easily_ if you have any function inside that use the `?` operator because lambdas can’t interact with the control flow of the caller.

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [January 20, 2021, 7:59pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/13 "2021-01-20T19:59:45Z")

</div>

I took a look at this proposal, as well as the link posted by @steffahn in the second post. While I agree that removing extra level of braces/indentation would be nice, I don’t think that `loop match` or `for match` should get specific syntax.

* * *

I am now highly off-topic, but personally the think that annoys me the most in term of extra indentation is this pattern:

```rust
match x {
    None => {
        return Err(...); // short exit early
    },
    Some(x) => {
        // use the unwrapped x
        ...
        // most of the code now has 2 extra level of indentation
    },
}

```

That’s two extra level of unwanted indentation, because lambda can’t modify the control flow of the caller. Assuming that the hypothetical `inline` keyword could do such thing, here is the kind of syntax I’d like:

```rust
let x = x.unwrap_or(inline || {
    return Err(...);
});
// x in now unwrapped
// the rest of the function doesn’t have extra indentation.

```

---

<div class="post-metadata">

**Author:** ![steffahn](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/steffahn/32/13288_2.png) [@steffahn](https://internals.rust-lang.org/u/steffahn)\
**Post date:** [January 20, 2021, 8:12pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/14 "2021-01-20T20:12:11Z")

</div>

How about

```rust
let x = x.ok_or_else(|| Err(...))?;

```

or even

```rust
let x = x.ok_or(Err(...))?;

```

in case of `...` being some literal/constant?

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [January 20, 2021, 8:27pm UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/15 "2021-01-20T20:27:01Z")

</div>

I will keep this is mind. That’s probably what I need. I’m surprised I didn’t saw it mentioned (maybe it was) in the last `if`/`unless` discussion I read here. If it effectively works everitime, you made my day!

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [January 21, 2021, 6:09am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/16 "2021-01-21T06:09:09Z")

</div>

Why not take advantage of the fact that you early-return anyway?

```rust
let x = match x {
    None => return Err(...),
    Some(x) => x,
};

// use `x` here without any additional indentation

```

---

<div class="post-metadata">

**Author:** ![robinm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/robinm/32/6255_2.png) [@robinm](https://internals.rust-lang.org/u/robinm)\
**Post date:** [January 21, 2021, 7:43am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/17 "2021-01-21T07:43:26Z")

</div>

> [@H2CO3](#):
>
> Why not take advantage of the fact that you early-return anyway?

The verbosity is way above java level of buraucratie! 🙂

---

<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:** [January 21, 2021, 8:33am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/18 "2021-01-21T08:33:26Z")

</div>

I'm looking forward to let-else syntax.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [January 21, 2021, 8:34am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/19 "2021-01-21T08:34:16Z")

</div>

It's a lot less verbose than your original… (and I'm now confused, because you originally wanted to reduce spurious indentation, so I'm feeling like we've got a moving goalpost here.)

---

<div class="post-metadata">

**Author:** ![system](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/system/32/14092_2.png) [@system](https://internals.rust-lang.org/u/system)\
**Post date:** [April 21, 2021, 8:34am UTC](https://internals.rust-lang.org/t/loop-match-for-match/13867/20 "2021-04-21T08:34:23Z")

</div>

Closed on April 21, 2021, 8:34am UTC

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.
