首页 > 解决方案 > 在HashSet中插入struct时的借用问题

问题描述

代码非常简单:在 HashSet 中插入一个结构,然后尝试使用它。我理解我得到的错误(移动后借用的价值),但我无法得到解决方案。

use std::collections::HashSet;

#[derive(PartialEq, Hash)]
struct MyStruct {
   s: String,
   n: i32
}

impl Eq for MyStruct {}

impl MyStruct {
   fn to_string(&self) -> String {
      format!("[s: {}, n: {}]", self.s, self.n)
   } 
}

fn main() {
   let s1 = MyStruct{ s: "aaa".to_string(), n: 50 };
   let s2 = MyStruct{ s: "bbb".to_string(), n: 100 };

   println!("s1 = {}", s1.to_string());

   let mut set: HashSet<MyStruct> = HashSet::new();
   set.insert(s1);

   // Here I get the error "Value borrowed after move"...
   // How can I use s1 or call its method to_string ?
   println!("s1 = {}", s1.to_string());
}

编译器输出:

  --> src\main.rs:28:24
   |
18 |    let s1 = MyStruct{ s: "aaa".to_string(), n: 50 };
   |        -- move occurs because `s1` has type `MyStruct`, which does not implement the `Copy` trait
...
24 |    set.insert(s1);
   |               -- value moved here
...
28 |    println!("s1 = {}", s1.to_string());
   |                        ^^ value borrowed here after move

您能否建议如何在 HashSet 中存储结构并在插入后继续使用它们?

谢谢

标签: structrusthashsetborrowing

解决方案


在夜间,您可以启用hash_set_entry并执行以下操作:

let s1 = set.get_or_insert(s1);

这将返回一个&MyStruct引用现在移动的值。

否则,如前所述,您可以使用Rc, 引用计数开销:

use std::rc::Rc;

let s1 = Rc::new(MyStruct{ s: "aaa".to_string(), n: 50 });
let mut set: HashSet<Rc<MyStruct>> = HashSet::new();
set.insert(s1.clone());
// s1 still works

或者您可以制作 aHashSet<&MyStruct>并插入&s1- 当然您需要s1HashSet.


推荐阅读