这个问题在这里已有答案:
我正在尝试将一对变量插入到HashSet
中,然后检查该对是否已存在。然后,我需要在相同的上下文中与该对进行下游工作。这是一个重现我的问题的游乐场:
use std::collections::HashSet;
fn main() {
let mut h = HashSet::new();
let a = 1;
let b = 2;
if h.contains(&(&a, &b)) {
println!("fail");
}
h.insert(&(&a, &b));
}
error[E0597]: borrowed value does not live long enough
--> src/main.rs:10:15
|
10 | h.insert(&(&a, &b));
| ^^^^^^^^ - temporary value dropped here while still borrowed
| |
| temporary value does not live long enough
11 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime
error[E0597]: `a` does not live long enough
--> src/main.rs:10:17
|
10 | h.insert(&(&a, &b));
| ^ borrowed value does not live long enough
11 | }
| - `a` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
error[E0597]: `b` does not live long enough
--> src/main.rs:10:21
|
10 | h.insert(&(&a, &b));
| ^ borrowed value does not live long enough
11 | }
| - `b` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
我如何检查a
和b
是否在集合中,然后如果不是,则将它们插入,然后用它们做其他事情?如果我在同一范围内加载对它们的引用,它们是如何被借用的?
暂时搁置“为什么”,所提出的例子有三个问题:
&(...)
就不再存在。因此,在HashSet::insert
返回后插入一个不存在的引用是一个错误,编译器幸运地捕获了一个错误。HashSet
,编译器将其视为错误(可能是因为在HashSet
范围内的某些点上,变量a
和b
不存在)。这是我多次被烧毁的东西,在编译器改进之前你应该记住这个限制。HashSet
s在插入时采用T
,在访问时使用&T
。您的代码使用T
。以下代码修复了这些问题:
use std::collections::HashSet;
fn main() {
let a = 1;
let b = 2;
let mut h = HashSet::new();
if h.contains(&(&a, &b)) {
println!("fail");
}
h.insert((&a, &b));
}
比较声明HashSet
并插入元组的行。