如何从HashMap或HashSet返回get_mut的结果?

时间:2019-06-19 22:12:17

标签: rust borrow-checker

我正在尝试包装如下定义的HashMap,以从HashMap返回可变的引用:

use std::{collections::HashMap, marker::PhantomData};

struct Id<T>(usize, PhantomData<T>);
pub struct IdCollection<T>(HashMap<Id<T>, T>);

impl<'a, T> std::ops::Index<Id<T>> for &'a mut IdCollection<T> {
    type Output = &'a mut T;
    fn index(&mut self, id: &'a Id<T>) -> Self::Output {
        self.0.get_mut(id).unwrap()
    }
}

以及由此产生的错误:

note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 54:5...
  --> src/id_container.rs:54:5
   |
54 | /     fn index(&mut self, id: &'a Id<T>) -> Self::Output {
55 | |         self.0.get_mut(id).unwrap()
56 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/id_container.rs:55:9
   |
55 |         self.0.get_mut(id).unwrap()
   |         ^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 52:6...
  --> src/id_container.rs:52:6
   |
52 | impl<'a, T> std::ops::Index<Id<T>> for &'a mut IdCollection<T> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::ops::Index<id_container::Id<T>>
              found std::ops::Index<id_container::Id<T>>

为什么编译器不能延长get_mut的生存期?然后IdCollection将被可变借用。

请注意,我尝试使用std::collections::HashSet<IdWrapper<T>>而不是HashMap

struct IdWrapper<T> {
  id: Id<T>,
  t: T,
}

实施适当的借用等,因此我可以使用Id<T>作为密钥。 但是,HashSet没有提供可变的getter(这很有意义,因为您不想突变用于哈希的内容)。但是,就我而言,对象的仅一部分应该是不可变的。将const类型转换为非const是UB,所以这是不可能的。

我可以实现我想要的吗?我是否必须使用诸如Box之类的包装器?尽管我宁愿避免任何间接...

编辑

好吧,我是个白痴。首先,我错过了IndexMut而不是Index,并且在签名中指定&时忘记了Self::Output

下面是我的完整代码:

pub struct Id<T>(usize, PhantomData<T>);
impl<T> std::fmt::Display for Id<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<T> Hash for Id<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T> PartialEq for Id<T> {
    fn eq(&self, o: &Self) -> bool {
        self.0 == o.0
    }
}
impl<T> Eq for Id<T> {}

pub struct IdCollection<T>(HashMap<Id<T>, T>);
impl<'a, T> IntoIterator for &'a IdCollection<T> {
    type Item = (&'a Id<T>, &'a T);
    type IntoIter = std::collections::hash_map::Iter<'a, Id<T>, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl<'a, T> IntoIterator for &'a mut IdCollection<T> {
    type Item = (&'a Id<T>, &'a mut T);
    type IntoIter = std::collections::hash_map::IterMut<'a, Id<T>, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter_mut()
    }
}

impl<T> std::ops::Index<Id<T>> for IdCollection<T> {
    type Output = T;
    fn index(&self, id: Id<T>) -> &Self::Output {
        self.0.get(&id).unwrap()
    }
}

impl<T> std::ops::IndexMut<Id<T>> for IdCollection<T> {
    fn index_mut(&mut self, id: Id<T>) -> &mut Self::Output {
        self.0.get_mut(&id).unwrap()
    }
}

impl<T> std::ops::Index<&Id<T>> for IdCollection<T> {
    type Output = T;
    fn index(&self, id: &Id<T>) -> &Self::Output {
        self.0.get(id).unwrap()
    }
}

impl<T> std::ops::IndexMut<&Id<T>> for IdCollection<T> {
    fn index_mut(&mut self, id: &Id<T>) -> &mut Self::Output {
        self.0.get_mut(id).unwrap()
    }
}

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您要达到的目标,那么我必须告诉您,它比您原本想的要复杂一些。

首先,您必须认识到,如果您喜欢使用HashMap,那么密钥的类型必须是 hashable comparable 。因此,必须将T中的通用类型参数Id<T>绑定到这些特征,以使Id具有可哈希性和可比性。

您需要了解的第二件事是处理索引操作符有两个不同的特征:Index用于不可变数据访问,IndexMut用于可变的访问。

use std::{
    marker::PhantomData,
    collections::HashMap,
    cmp::{
        Eq,
        PartialEq,
    },
    ops::{
        Index,
        IndexMut,
    },
    hash::Hash,
};

#[derive(PartialEq, Hash)]
struct Id<T>(usize, PhantomData<T>)
    where T: PartialEq + Hash;

impl<T> Eq for Id<T>
    where T: PartialEq + Hash
{}

struct IdCollection<T>(HashMap<Id<T>, T>)
    where T: PartialEq + Hash;

impl<T> Index<Id<T>> for IdCollection<T>
    where T: PartialEq + Hash
{
    type Output = T;

    fn index(&self, id: Id<T>) -> &Self::Output
    {
        self.0.get(&id).unwrap()
    }
}

impl<T> IndexMut<Id<T>> for IdCollection<T>
    where T: PartialEq + Hash
{
    fn index_mut(&mut self, id: Id<T>) -> &mut Self::Output
    {
        self.0.get_mut(&id).unwrap()
    }
}

fn main()
{
    let mut i = IdCollection(HashMap::new());
    i.0.insert(Id(12, PhantomData), 99i32);
    println!("{:?}", i[Id(12, PhantomData)]);
    i[Id(12, PhantomData)] = 54i32;
    println!("{:?}", i[Id(12, PhantomData)]);
}

这似乎有些令人惊讶,但是IndexMut并非旨在将元素插入到集合中,而是实际上修改了现有元素。这是HashMap不实现IndexMut的主要原因-这也是上面的示例使用HashMap::insert方法初始放置数据的原因。如您所见,稍后,当该值可用时,我们可以通过IdCollection::index_mut对其进行修改。

相关问题