Idea: SliceIndex by Options and/or Results

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 Errs 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?

Aside, note that impl From<u16> for usize does exist, just not from u32 or u64.

Anyway, I feel like writing .get(i.try_into()?) would be more idiomatic for fallible lookups. For panicking index, while your examples do make some sense to associate with out-of-bounds panics, that seems more dubious for arbitrary Option<usize> or Result<usize, _>.

edit: I’m warming a little as I think more, because it does seem like a small ergonomic win. Not sure.

The trouble I see there is that .get(i.try_into()?)? wouldn't work because one of the ?s is on Option and the other is on Result, so collapsing the two as part of SliceIndex might make that easier to use.

Well, there’s also .ok() to “normalize” errors as None.

As well as NoneError.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.