HashSet中插入struct时的借用问题

Borrowing problem when inserting struct in HashSet

代码非常简单:在 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 中并在插入后继续使用它们?

谢谢

每晚您可以启用 hash_set_entry 并执行:

let s1 = set.get_or_insert(s1);

这将 return 一个 &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

或者您可以创建一个 HashSet<&MyStruct> 并插入 &s1 - 当然您需要在 HashSet 期间保持 s1 活动。