# Mini idea: slice length patterns

**URL:** <https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994>\
**Category:** language design\
**Created:** [December 7, 2023, 1:53am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994 "2023-12-07T01:53:32Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 1:53am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/1 "2023-12-07T01:53:33Z")

</div>

In today's Rust, you can use pattern-matching to check that a slice has a specific length:

```rust
match slice {
    &[_, _, _] => println!("slice has length 3"),
    _ => (),
}

```

Or check that it has a minimum length:

```rust
match slice {
    &[_, _, .., _] => println!("slice has length at least 3"),
    _ => (),
}

```

But you can't constrain its maximum length without an `if` guard (that exhaustiveness checking doesn't understand). And if the length you want to check for is large, the syntax becomes unwieldy:

```rust
match slice {
    &[_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _] => println!("slice has length 21"),
    _ => (),
}

```

To remedy this, the syntax for specifying array lengths could be adapted to work with slice patterns:

```rust
match slice {
    &[..; 21] => println!("slice has length 21"),
    _ => (),
}

```

```rust
match slice {
    &[..; 13..=23] => println!("slice has length between 13 and 23"),
    _ => (),
}

```

```rust
match slice {
    &[.., 0; 13..=23] => println!("slice has length between 13 and 23, with last element 0")
    _ => (),
}

```

---

<div class="post-metadata">

**Author:** ![pitaj](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/pitaj/32/11262_2.png) [@pitaj](https://internals.rust-lang.org/u/pitaj)\
**Post date:** [December 7, 2023, 1:58am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/2 "2023-12-07T01:58:34Z")

</div>

One question I have is how can this compose with normal slice patterns?

Can the following work?

```rust
match slice {
    &[first, ..; 30, last] => { ... }
}

```

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 2:05am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/3 "2023-12-07T02:05:52Z")

</div>

I would expect that to be written `[first, .., last; 31]`.

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [December 7, 2023, 2:48am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/4 "2023-12-07T02:48:23Z")

</div>

Is the `..` required? If not, what's the behavior of a length mismatch?

In particular, what is the behavior or error here?

```rust
fn hmm(arr: &[i32; 256]) {
    match arr {
        [0; 256] => {}
        [1; 256] => {}
        _ => {}
    }
}

```

And would it preclude this from ever working:

```rust
fn hmm<const N: usize>(arr: &[i32; N]) {
    match arr {
        [0; N] => {}
        [1; N] => {}
        _ => {}
    }
}

```

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 2:53am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/5 "2023-12-07T02:53:45Z")

</div>

I would expect any length mismatch to be a compile error. So `[1; 17]` is an error, and so are `[1, 2; 12..]` and `[1, 2, .., 3, 7; ..=3]`.

I suppose `[1; 256]` having a different meaning in expression and pattern position would be confusing, though... Good catch! (It wouldn't be the first such case; `0 | 1` also has different meaning in expression vs pattern position.)

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 3:04am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/6 "2023-12-07T03:04:07Z")

</div>

> [@quinedot](#):
>
> And would it preclude this from ever working:
> 
> ```rust
> fn hmm<const N: usize>(arr: &[i32; N]) {
> match arr {
> [0; N] => {}
> [1; N] => {}
> _ => {}
> }
> }
> 
> ```

With generic constants, this would still be expressible (though far more verbose):

```rust
fn hmm<const N: usize>(arr: &[i32; N]) {
    const ZEROS<const N: usize>: [i32; N] = [0; N];
    const ONES<const N: usize>: [i32; N] = [1; N];
    match arr {
        ZEROES<N> => {}
        ONES<N> => {}
        _ => {}
    }
}

```

---

<div class="post-metadata">

**Author:** ![pitaj](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/pitaj/32/11262_2.png) [@pitaj](https://internals.rust-lang.org/u/pitaj)\
**Post date:** [December 7, 2023, 3:13am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/7 "2023-12-07T03:13:46Z")

</div>

I'm confused. How is the meaning different?

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 3:17am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/8 "2023-12-07T03:17:56Z")

</div>

In expression position, `[1; 256]` is an array of 256 1's. In pattern position under this proposal, it's an array of length 256 that contains a single element equal to 1 (this being an impossibility, the pattern would be rejected).

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [December 7, 2023, 3:30am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/9 "2023-12-07T03:30:01Z")

</div>

Right, it precludes shorthand literal array syntax in patterns directly.\[1\] Perhaps more of a diagnostic issue than anything. At least, if the "unsatisfiable length is an error" approach is taken.

(The current diagnostics are already funky, as they assume you meant `,` instead of `;` and soldier on mumbling about length 2 mismatches and potentially type mismatches.)

* * *

I was thinking it's somewhat nicer if the length and slice portions are independent, in a [trivial bounds](https://rust-lang.github.io/rfcs/2056-allow-trivial-where-clause-constraints.html) sort of way. But I also think it would be pretty foot-gunny to allow overlap between array shorthand and slice length patterns without the unsatisfiable length errors; worthy of a default deny or at least warning lint.

Or just require `..` if there's a length pattern.

But it turns out [there's some precedent for erroring on unsatisfiable lengths already.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fabcf6dd1e351bb27aadaa36c53478ad) So perhaps the thought is mostly "Alternatives" fodder.

* * *

1. Unless they happen to be length 1, sorta.

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 3:34am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/10 "2023-12-07T03:34:39Z")

</div>

> [@quinedot](#):
>
> But it turns out [there's some precedent for erroring on unsatisfiable lengths already.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fabcf6dd1e351bb27aadaa36c53478ad)

As I've written elsewhere, [variadic generics could potentially benefit from relaxing that restriction](https://hackmd.io/@x5qEAKM5Q36wKV_Wftw96g/HJFy6uzDh#matching-over-tuples-of-different-arities), so I don't think it's a crazy idea.

---

<div class="post-metadata">

**Author:** ![pitaj](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/pitaj/32/11262_2.png) [@pitaj](https://internals.rust-lang.org/u/pitaj)\
**Post date:** [December 7, 2023, 3:40am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/11 "2023-12-07T03:40:28Z")

</div>

What about allowing the "semicolon repeat" number after any element, but it only applies to the immediately preceding element?

Then `[1; 256]` means the same thing in pattern or expression position. The only issue is that the number after the semicolon is no longer always the length of the whole array / slice.

But I think that opens things up a bit because then you can do things like `[start @ _; 16, ..]`

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/quinedot/32/7294_2.png) [@quinedot](https://internals.rust-lang.org/u/quinedot)\
**Post date:** [December 7, 2023, 4:29am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/12 "2023-12-07T04:29:35Z")

</div>

[Related comment about the interaction of (exclusive/from) slice patterns and range patterns.](https://github.com/rust-lang/rust/issues/67264#issuecomment-854921128) (Though `..=` is stable in slice patterns and doesn't mean "ranging slice".)

---

<div class="post-metadata">

**Author:** ![Jules-Bertholet](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jules-bertholet/32/10671_2.png) [@Jules-Bertholet](https://internals.rust-lang.org/u/Jules-Bertholet)\
**Post date:** [December 7, 2023, 4:31am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/13 "2023-12-07T04:31:18Z")

</div>

> [@pitaj](#):
>
> allowing the "semicolon repeat" number after any element

Nesting `;` "inside" `,` isn't consistent with English or intuition (less prominent separator should nest between more prominent separator).

> [@pitaj](#):
>
> But I think that opens things up a bit because then you can do things like `[start @ _; 16, ..]`

Other possible syntaxes would be `[..[..start; 16], ..]` or `[start @ ..[..; 16], ..]`, though those are pretty ugly...

---

<div class="post-metadata">

**Author:** ![pitaj](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/pitaj/32/11262_2.png) [@pitaj](https://internals.rust-lang.org/u/pitaj)\
**Post date:** [December 7, 2023, 5:11am UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/14 "2023-12-07T05:11:49Z")

</div>

> [@Jules-Bertholet](#):
>
> Nesting `;` "inside" `,` isn't consistent with English or intuition (less prominent separator should nest between more prominent separator).

I don't think it's that bad. Colons are usually only allowed before a list in English. Plus, in most cases it's going to be at the end anyways. But if people hate it that much, another alternative is putting them in parens:

```rust
match slice {
    &[1; 10] => ...
    &[(2; 11), last] => ...
}

```

---

<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:** [December 7, 2023, 12:08pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/15 "2023-12-07T12:08:43Z")

</div>

I think making `..` mandatory when there's length mismatch would help to disambiguate it.

Mandatory `..` would be more in line with structs. Not having to write `[_, _, _, _, _]` is a different feature from a syntax sugar for matching against `[1, 1, 1, 1, 1]`. In structs you have `..` to skip fields, but there isn't any syntax to match all fields against a value.

---

<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:** [December 7, 2023, 12:10pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/16 "2023-12-07T12:10:45Z")

</div>

> [@quinedot](#):
>
> nd would it preclude this from ever working:
> 
> `fn hmm<const N: usize>(arr: &[i32; N]) {`

It could be a monomorphisation-time error, e.g. `[1,2,3,4,5,..; N]` where `N < 5`. Or rather if it wasn't an error, it'd be weird to silently allow impossible pattern.

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [December 7, 2023, 1:32pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/17 "2023-12-07T13:32:37Z")

</div>

(Edit: to be clear, I'd be fine if patterns like `[1; 4]` just failed to compile; slice len patterns would be valuable in any case.)

I’d expect that `[1; 4]` would mean the same in pattern and expression positions, ie. shorthand for `[1, 1, 1, 1]`. `[1, ..; 4]` as a pattern could mean any 4-len array/slice with first element 1. The `[x; N]` pattern would then admittedly be a special case, being the "repeat x" pattern, whereas `[1, 2; 4]` would fail to compile. `[1, 2, 3, 4; 4]` could compile but would be redundant.

More generally, the `[<pat>; 4]` pattern could mean a 4-len array/slice each element of which matches `<pat>`: `[1..; 4]` would mean a 4-len array/slice with every element at least one, but it might be too confusing/error-prone :\< Also, it would be unclear what `[a; 4]` (or `[a @ <pat>; 4]`) means – what would `a` bind to and what would its type be?

(On the expression side it would be nice if splats like `[1, ..Default::default(); N]` worked and mirrored the corresponding pattern, but `..x` of course conflicts with the `RangeTo` constructor – this is why I’d like `...` to be repurposed to a splatting operator now that it’s free. It could also be confusing why `[2, ...1; 10]` doesn’t work and you’d have to write something like `[2, ...[1; _]; 10]` although it’s consistent with how struct update syntax works.)

---

<div class="post-metadata">

**Author:** ![afetisov](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/afetisov/32/8508_2.png) [@afetisov](https://internals.rust-lang.org/u/afetisov)\
**Post date:** [December 8, 2023, 1:20pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/18 "2023-12-08T13:20:05Z")

</div>

If you just want to check slice's length, just call its `len()` method. I don't see the point of this feature. The use cases where one uses slice patterns usually involve extracting the respective elements from the slice, and the proposed feature doesn't have any affordances for that. What would be the use cases where your new patterns would actually be the best solution?

---

<div class="post-metadata">

**Author:** ![Mokuz](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mokuz/32/7225_2.png) [@Mokuz](https://internals.rust-lang.org/u/Mokuz)\
**Post date:** [December 8, 2023, 3:00pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/19 "2023-12-08T15:00:25Z")

</div>

Main benefit is being able to convert a slice to an array if the length matches.

```rust
fn foo(array: &[i32; 4]) {
    // do stuff
}

fn baz(slice: &[i32]) {
    match slice {
        array @ [..; 4] => foo(array),
        _ => { /* do something else */ }
    }
 }

```

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [December 8, 2023, 4:45pm UTC](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994/20 "2023-12-08T16:45:25Z")

</div>

Though in many cases you can also use the TryFrom/TryInto `&[T]` -\> `&[T; N]` conversion.

[Next page](https://internals.rust-lang.org/t/mini-idea-slice-length-patterns/19994.md?page=2)
