Idea: const range slicing outputs an array (reference) rather than slice (reference)

The output of the range slicing is now a (&)[T]. If the range is const and a (&)[T; N] is needed, an extra try_into() will be required with completely redundant check. Can we specify a syntax or function that outputs (&)[T; N] for const range slicing?

1 Like

The redundant check will almost certainly be optimized away, but you could also encapsulate it with a newtype index like this:

pub struct ArrayIndex<const N: usize>(usize);

impl<T, const N: usize> std::ops::Index<ArrayIndex<N>> for [T] {
    type Output = [T; N];

    fn index(&self, ai: ArrayIndex<N>) -> &[T; N] {
        (&self[ai.0..][..N]).try_into().unwrap()
    }
}

impl<T, const N: usize> std::ops::IndexMut<ArrayIndex<N>> for [T] {
    fn index_mut(&mut self, ai: ArrayIndex<N>) -> &mut [T; N] {
        (&mut self[ai.0..][..N]).try_into().unwrap()
    }
}

There's some discussion of this in ACP: slice::{split_,}{first,last}_chunk · Issue #69 · rust-lang/libs-team · GitHub

.first_chunk::<N>(), for example, could be the way to do this.

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