Try_into error message

Consider this code:

let a: [u16; 3];
let ord: u8 = a.len().try_into().unwrap() - 1;

The try_into() part is giving this error message that looks cryptic:

type annotations needed
cannot infer type for type parameter U

note: cannot satisfy _: std::convert::TryFrom<usize>
note: required because of the requirements on the impl of std::convert::TryInto<_> for usizerustc(E0283), 19): this method call resolves to std::result::Result<T, <Self as std::convert::TryInto<T>>::Error>, 27): cannot infer type for type parameter U

Could you please tell me what does it want from me? :slight_smile:

The compiler is not able to figure out what type the length should be converted into. All it knows is that it's a type you can subtract some integer from and get an u8, but since there could be many such types, this is not fully constrained. For example, you could even define your own custom type and implement both TryInto<YourType> for usize and YourType - i32 with output type u8. This would fit the constraints.


Here is a way to constrain it.

// succeeds for a.len() of 1..=255, underflows u8 for 0
let ord = TryInto::<u8>::try_into(a.len()).unwrap() - 1;

Here's another, but beware that it has different behavior.

// succeeds for a.len() of 1..=256
let ord: u8 = (a.len() - 1).try_into().unwrap();

Thank you!