Why does the index method require ownership?

In documents, the sign is determined Index:

pub trait Index<Idx> where Idx: ?Sized {
    type Output: ?Sized;
    fn index(&self, index: Idx) -> &Self::Output;
}

Since the type of the parameter Index Idx, and not &Idx, the method Indexshould take responsibility for the value passed.

Is there a reason for this limitation? I know that 9 times out of 10 will use something like an integer type that outputs Copy, but I'm just wondering why the borrowed value will be less capable of acting like an index.

+4
source share
1 answer

A borrowed value can be a very good index, and this allows you to define a characteristic Index. Just use the link as the index type. An example of nonsense:

impl <'a> Index<&'a IndexType> for Foo {
    type Output = u8;
    fn index(&self, index: &IndexType) -> &u8 {
        unimplemented!()
    }
}

, "" , , Index, , .

+4

Source: https://habr.com/ru/post/1615887/


All Articles