Pre-RFC: Constant slicing


#1

Problem statement

Currently the standard practice for code is to use slices as input arguments, even if it’s known that function must accept only fixed length input. One of the reasons for it is references to arrays (i.e. [T; 5]) can feel the second order citizens compared to slices, due to the traits being implemented only for sizes up to 32. This should be soon solved by this RFC. But other reason is that taking array references from an existing buffer is unergonomic and simply not possible in safe Rust.

Because of it existing code often omits important information from the API type signature, which can have negative impact on the performance and soundness of the code.

#Proposal I would like to propose to add the second slicing type, the constant one. Essentially it will be a syntactic sugar to [arrayref] (https://crates.io/crates/arrayref) crate macro and can look like &foo[N:M], where N and M required to be usize constants (generic or {integer}), and &foo must provide Derefs for [T]. As a result this expression will return &[T; M-N], if M > foo.len() or N > M it will panic. &foo[:M] will be equivalent to N = 0 and &foo[N:] will be allowed only if foo is an array, so M can be taken as foo.len().

Syntax can be changed to something else to avoid possible ambiguity.

#Alternatives Leave everything as is. Teach about arrayref crate.


#2

This isn’t really possible yet without compiler magic or type level integers.

RFC issues https://github.com/rust-lang/rfcs/issues/1772 and https://github.com/rust-lang/rfcs/issues/1833 talk about this feature with some more detail on possible implementations.


#3

Ah, couldn’t find those issues while searching for something relevant.

It would be definitely cool to implement “value refinement” approach from the first issue, but I am not sure if it’s possible to do it in a backward compatible way. Thus proposal for a new syntax.