struct - 在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 中存储结构并在插入后继续使用它们?
谢谢
解决方案
在夜间,您可以启用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
- 当然您需要s1
在HashSet
.
推荐阅读
- intellij-idea - Scalatest 在 Intellij 中与 Scala 2.13.0 一起工作需要什么?
- networking - 如何使用 nodejs 应用程序在两个 pod 之间进行通信
- swift - 当应用程序被“杀死”时,尝试将我的计时器保存到 UserDefaults
- powershell - 读取 CSV 文件,然后拆分值并创建一个全局变量
- sql - 附加查询将数据相乘
- python - Flask - 将列表传递给新视图
- django - 如何从 ddesktop 计算机到我的笔记本电脑继续处理 pycharm 中现有的 django 项目?
- python - 如何在 libvirt xml 中使用 ivshmem-plain?
- function - 如何从您的指标脚本中引用另一个指标中的函数?
- android - 侦听按钮单击并将片段与视图模型链接