I was sad to notice today that this doesn’t work:
use std::convert::TryInto;
pub fn indexed(x: &[i32], i: u16) -> i32 {
x[i.try_into().unwrap()]
}
Because it has inference trouble:
error[E0283]: type annotations required: cannot resolve `_: std::convert::TryFrom<u16>`
--> <source>:3:9
|
3 | x[i.try_into().unwrap()]
| ^^^^^^^^
|
= note: required because of the requirements on the impl of `std::convert::TryInto<_>` for `u16`
But it made me wonder whether we could just allow indexing of slices by Result
, with Err
s always failing the lookup. Then we wouldn’t have to type the .unwrap()
– which would be convenient regardless – and would still panic in the same situations as we do today, but could also do things like .get(i.try_into())
for fallible lookups nicely.
Allowing Option
too would be consistent, and would open some potentially-interesting things like
x[i.checked_add(j)]
Thoughts?