Struct 在哈希集中插入结构时出现借用问题
代码非常简单:在哈希集中插入一个结构,然后尝试使用它。我理解我得到的错误(移动后借用的值),但我无法得到解决方案Struct 在哈希集中插入结构时出现借用问题,struct,rust,hashset,borrowing,Struct,Rust,Hashset,Borrowing,代码非常简单:在哈希集中插入一个结构,然后尝试使用它。我理解我得到的错误(移动后借用的值),但我无法得到解决方案 使用std::collections::HashSet; #[派生(PartialEq,散列)] 结构MyStruct{ s:弦, n:i32 } MyStruct{}的impl Eq impl MyStruct{ fn到_字符串(&self)->字符串{ 格式!(“[s:{},n:{}]”,self.s,self.n) } } fn main(){ 设s1=MyStruct{s:
使用std::collections::HashSet;
#[派生(PartialEq,散列)]
结构MyStruct{
s:弦,
n:i32
}
MyStruct{}的impl Eq
impl MyStruct{
fn到_字符串(&self)->字符串{
格式!(“[s:{},n:{}]”,self.s,self.n)
}
}
fn main(){
设s1=MyStruct{s:“aaa.”to_string(),n:50};
设s2=MyStruct{s:“bbb.”to_string(),n:100};
println!((“s1={}”,s1.to_string());
让mut set:HashSet=HashSet::new();
插入(s1);
//这里我得到了错误“移动后借用的值”。。。
//如何使用s1或调用其方法以生成字符串?
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中存储结构并在插入后继续使用它们吗
感谢您在夜间,您可以启用并执行以下操作:
它将返回一个引用当前移动值的&MyStruct
否则,如前所述,您可以使用Rc
,其refcounting开销包括:
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
使用std::rc::rc;
让s1=Rc::new(MyStruct{s:“aaa.”to_string(),n:50});
让mut set:HashSet=HashSet::new();
set.insert(s1.clone());
//s1仍然有效
或者你可以制作一个
HashSet
并插入&s1
——当然你需要在HashSet
期间保持s1
处于活动状态,这可能是TL的重复;DR:您不能按原样使用,必须使用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