Vector 尝试索引到Rust中的向量时出现SliceIndex特性绑定未满足的错误

Vector 尝试索引到Rust中的向量时出现SliceIndex特性绑定未满足的错误,vector,indexing,rust,Vector,Indexing,Rust,我有一个结构: pub struct SomeCollection<'a> { items: Vec<&'a SomeValue>, name_mapping: HashMap<&'a str, usize>, index_mapping: HashMap<&'a str, usize> } impl<'a> Index for SomeCollection<'a> {

我有一个结构:

pub struct SomeCollection<'a> {
    items: Vec<&'a SomeValue>,
    name_mapping: HashMap<&'a str, usize>,
    index_mapping: HashMap<&'a str, usize>
}

impl<'a> Index for SomeCollection<'a> {
    type Output = Option<&'a SomeValue>;

    fn index(&self, value_name: &str) -> &Self::Output {
        match self.name_mapping.get(value_name) {
            Some(index) => &self.items.get(index),
            None => match self.index_mapping.get(value_name) {
                Some(index) => &self.items.get(index),
                None => &None
            }
        }
    }
}
当我尝试编译此代码时,出现以下错误:

error[E0277]: the trait bound `&usize: std::slice::SliceIndex<[&SomeValue]>` is not satisfied
  --> src\some_collection.rs:49:48
   |
49 |                 Some(index) => &self.items.get(index),
   |                                            ^^^ slice indices are of 
type `usize` or ranges of `usize`
   |
   = help: the trait `std::slice::SliceIndex<[&SomeValue]>` is not implemented for `&usize`
Rust似乎在告诉我,我不能用索引索引到一个向量中,这是一个usize。我不确定为什么我需要实现这个特性,因为它应该已经为默认向量实现了。有谁能告诉我我犯这个错误的真正原因吗?此代码中可能还有其他尚未出现的错误,请在回答时记住这一点

Rust似乎在告诉我,我不能用索引索引到一个向量中,这是一个usize

不,编译器告诉您不能使用&usize索引向量

只需使用*索引即可解决此特定问题。但是,您的代码还有其他问题:

索引特征需要一个类型参数,例如本例中的&str。 index方法通常只能返回对存储在正在编制索引的数据结构中的数据的引用。您的代码创建一个临时选项,该选项不存储在原始数据中,然后尝试返回对该选项的引用。如果这正是您想要做的,那么您需要定义自己的方法或特性,以代替按值返回选项。
也许编译器错误很难理解,但至少它是准确的。它告诉您,该索引是一个引用&usize,但是Vec只能使用值usize进行索引。所以你所要做的就是去引用索引

此外,如果找不到键/索引,通常索引恐慌。这就是为什么标准库将Vec::get和HashMap::get作为单独的方法与索引一起提供,如果给定的键/索引不在集合中,它们不会死机,但不会返回None

恳求{ 输入Output=&'a SomeValue; fn索引和self,值\名称:&str->&self::输出{ 匹配self.name\u mapping.getvalue\u name{ Someindex=>&self.items[*index], 无=>匹配self.index\u mapping.getvalue\u名称{ Someindex=>&self.items[*index], None=>panic!缺少键:{:?},值\名称, } } } }
请发布一个代码,重现您的错误。我相信您的完整代码应该是这样的:
the trait `std::slice::SliceIndex<[&SomeValue]>` is not implemented for `&usize`