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.
camsteffen:
but it fails to compile
I think this is, at least in part, a fixable inference issue:
opened 08:48PM - 04 Sep 20 UTC
closed 01:36PM - 03 Aug 23 UTC
C-enhancement
E-medium
A-inference
A-const-generics
A-array
Simple demo <https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018… &gist=5b0acd8b21c773c9c4a3ff73bc7a030e>:
```rust
#![allow(unused_variables)]
struct Zeroes;
impl Into<[usize; 2]> for Zeroes {
fn into(self) -> [usize; 2] { [0; 2] }
}
impl Into<[usize; 3]> for Zeroes {
fn into(self) -> [usize; 3] { [0; 3] }
}
impl Into<[usize; 4]> for Zeroes {
fn into(self) -> [usize; 4] { [0; 4] }
}
fn main() {
let [a, b, c] = Zeroes.into(); // ERROR: type annotations needed
let [d, e, f]: [_; 3] = Zeroes.into(); // Works great
}
```
This is presumably not happening because slice patterns in refutable patterns can be more than just an array of that exact size, but there's no other option for **ir**refutable patterns.
This would be particularly helpful as we're getting more and more `[T; N]: TryFrom<_>` implementations with const generics. See the example in https://github.com/rust-lang/rust/pull/76310 for the place I first noticed this not working the way I'd hoped.
Zulip topic: https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Type.20inferrence.20.26.20irrefutable.20slice.20patterns/near/209052937
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
system
Closed
October 19, 2021, 10:27pm
8
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.