Add `slice::as_array_ref`

On more than one occasion I have tried to write something like this

let [n] = slice.try_into()?; // ERROR cannot infer T

but it fails to compile. So I do this.

let [n] = <&[_; 1]>::try_from(slice)?;

but that is no fun. I would like to have slice::as_array_ref() so I can do this:

let [n] = slice.as_array_ref()?;

Edit: I changed my examples from if let to ? since that is actually more compelling - if let can just use slice patterns.

This would also help with doc visibility.

There could be to_array() where T: Copy as well.

For some context, this is a very common question and the old arrayref crate is still getting 20k+ downloads daily.

I think this is, at least in part, a fixable inference issue:

4 Likes

That would be ideal if try_into just works. If that issue were fixed, would the compiler be able to infer the element type of the array as well, for try_into?

Actually I already answered my own question because I used <&[_; 1]>::try_from.

1 Like