Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the index method require ownership?

Tags:

rust

From the docs, the Index trait is defined:

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

Since the type of the index parameter is Idx and not &Idx, the index method needs to take ownership of the value it is passed.

Is there a reason for this restriction? I know 9 times out of 10 one will be using something like an integer type that derives Copy, but I'm just curious why a borrowed value would be any less capable of acting as an index.

like image 232
jobo3208 Avatar asked Sep 26 '22 05:09

jobo3208


1 Answers

A borrowed value can be a perfectly good index, and the definition of the Index trait allows for that. Just use a reference as the index type. Nonsense example:

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

So the "restriction" of passing the index by value isn't really a restriction at all, because it allows the person implementing Index to choose if the index should be passed by value or by reference.

like image 180
fjh Avatar answered Sep 29 '22 16:09

fjh