将对变量的引用插入到HashSet中,然后使用变量[duplicate]

问题描述 投票:0回答:1

我正在尝试将一对变量插入到HashSet中,然后检查该对是否已存在。然后,我需要在相同的上下文中与该对进行下游工作。这是一个重现我的问题的游乐场:

https://play.rust-lang.org/?gist=5eecfa9c1e54b468d79955aab916dd84&version=stable&mode=debug&edition=2015

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

我如何检查ab是否在集合中,然后如果不是,则将它们插入,然后用它们做其他事情?如果我在同一范围内加载对它们的引用,它们是如何被借用的?

rust
1个回答
2
投票

暂时搁置“为什么”,所提出的例子有三个问题:

  1. 一旦函数调用结束,元组&(...)就不再存在。因此,在HashSet::insert返回后插入一个不存在的引用是一个错误,编译器幸运地捕获了一个错误。
  2. 您在要引用的变量之前声明了HashSet,编译器将其视为错误(可能是因为在HashSet范围内的某些点上,变量ab不存在)。这是我多次被烧毁的东西,在编译器改进之前你应该记住这个限制。
  3. 正如上面的评论所指出的,HashSets在插入时采用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));
}

playground

比较声明HashSet并插入元组的行。

© www.soinside.com 2019 - 2024. All rights reserved.