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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With