rfcs icon indicating copy to clipboard operation
rfcs copied to clipboard

`TryIndex` and `TryIndexMut`

Open Jakobeha opened this issue 3 years ago • 2 comments

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NotFound<Idx> {
    pub index: Idx
}

pub trait TryIndex<Idx> {
    type Output;

    fn try_index(&self, index: Idx) -> Result<&Self::Output, NotFound<Idx>>;
}

pub trait TryIndexMut<Idx> {
    fn try_index_mut(&mut self, index: Idx) -> Result<&mut Self::Output, NotFound<Idx>>;
}

Do others support something like this?

The benefit of it being in the standard library is that we can use a subscript notation. Another benefit, over get and get_mut specifically, is that it's a trait, so we can pass around T: TryIndex members and implement it for multiple types of indices.

a[b] is already taken by Index, so we would have to use an alternate syntax like a?[b]. Alternatively we can just ditch subscript and rename try_index and try_index_mut to get and get_mut. It still may be a good idea to add to the standard library, because crates will derive TryIndex instead of providing their own get and get_mut which is not in a trait.

The main drawback of course is standard library bloat. There is try_traits which has TryIndex, but it only has around 9,000 downloads.

Another issue is redundancy and slight API differences, as get usually returns an Option, but here we return a Result which gives back the index. Some other crates do this as well, with their own NotFound error. Result is more "idiomatic" since mis-indexing is often an error, and useful for cases where Idx is not something you can copy. Though Idx being any more than a reference or number is very uncommon

Jakobeha avatar Aug 14 '22 19:08 Jakobeha

You haven't said a single word about why this would be useful. And you haven't given any concrete examples in real code either.

Result is more "idiomatic" since mis-indexing is often an error,

I don't agree.

BurntSushi avatar Aug 14 '22 19:08 BurntSushi

If we had a GAT-ified Index, you could build this on top of it with Result, Option, or anything you desire.

Noratrieb avatar Sep 08 '22 05:09 Noratrieb

You haven't said a single word about why this would be useful. And you haven't given any concrete examples in real code either.

I, personally, like the idea of a?[b]. Are you asking why syntax sugar is useful?

I don't agree about returning a Result<T,E> though.

colejohnson66 avatar Jun 19 '23 14:06 colejohnson66

Are you asking why syntax sugar is useful?

No.......

BurntSushi avatar Jun 19 '23 14:06 BurntSushi