为什么索引方法需要所有权?

job*_*208 5 rust

从文档中,Index定义了特征:

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

由于index参数的类型是Idx和否&Idx,因此该index方法需要获取它传递的值的所有权.

有这个限制的原因吗?我知道10次中有9次会使用类似于派生的整数类型的东西Copy,但我只是好奇为什么借用的值会更少能够充当索引.

fjh*_*fjh 4

借用的值可以是一个非常好的索引,并且Index特征的定义允许这一点。只需使用引用作为索引类型即可。废话举例:

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

因此,按值传递索引的“限制”根本不是真正的限制,因为它允许实现者Index选择索引是应按值传递还是按引用传递。