2

I have a Rust [i32; 6] that I'd like to split into three [i32; 2]. Can this be done by pattern matching, or do I explicitly have to reference all six elements?

I'd like to do something like this:

let arr6 = [0, 1, 2, 3, 4, 5];
let [sub1 @ [_; 2], sub2 @ [_; 2], sub3 @ [_; 2]] = arr6;
// or
let [sub1 @ [_, _], sub2 @ [_, _], sub3 @ [_, _]] = arr6;

Currently the only solution I see is

let sub1 = [arr6[0], arr6[1]];
let sub2 = [arr6[2], arr6[3]];
let sub3 = [arr6[3], arr6[4]]; // <-- whoops, that's wrong
1
  • Sounds like you're after the (currently unstable) as_chunks method. I think the closest thing that the stable standard library provides would be to iterate (and collect?) via chunks_exact, though of course (with unsafe) you could also reimplement the unstable API yourself. Commented Feb 23 at 12:16

1 Answer 1

2

Rust does not support sub-array patterns. It does support slice patterns, but that's going to yield a slice, and you can only have one of those as they don't have a length.

What you can do is either:

  1. match individual items then patch in, basically your version but without indices and hopefully the lower amount of "noise" makes error easier to spot

    let [a, b, c, d, e, f] = arr;
    let sub1 = [a, b];
    let sub2 = [c, d];
    let sub3 = [e, f];
    
  2. slice::chunks then convert the sub-slices back into arrays, although sadly that's a fair amount of runtime checking

    let arr = [1, 2, 3, 4, 5, 6];
    let (a, b, c) = arr.chunks(2)
       .map(<[_;2]>::try_from)
       .map(Result::unwrap)
       .collect_tuple()
       .unwrap();
    println!("{a:?} {b:?} {c:?}");
    

There is currently no fixed-size split, at least not in the stdlib, and current proposal would yield an array and a slice as const generics currently aren't powerful enough to handle split_at([T;N], M) -> ([T;M], [T;N-M]).

Sign up to request clarification or add additional context in comments.

4 Comments

If you use slice::chunks_exact the optimizer should be able to remove all the runtime checks (it might for chunks, too, but the former is easier to optimize.
What's collect_tuple? It's not a method on Iterator in std
True, and I even linked to the right one (since there is no wrong one because the std doesn't have an Iterator::chunks, that's also in itertools, and in that case Itertools::tuples() would make a lot more sense)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.