gpt4 book ai didi

rust - Rust不能在hashmap中插入不同的结构

转载 作者:行者123 更新时间:2023-12-03 11:41:00 26 4
gpt4 key购买 nike

假设我有一个结构体,并且想将其散列为2个HashMap,这样第一个结构体就拥有对该结构体的引用,而第二个结构体则具有对它的引用,如下所示:

struct Person { id: i32 }

fn main() -> std::io::Result<()> {
let mut first_name_table = HashMap::new();
let mut last_name_table = HashMap::new();

let person1 = Person { id: 1};
let first_name1 = "first1";
let last_name1 = "last1";

last_name_table.insert(last_name1, &person1);
first_name_table.insert(first_name1, person1);

Ok(())
}
这可以正常工作,并且符合预期。但是,当我尝试插入第二个人时,借阅检查器会出现以下错误:
struct Person { id: i32 }

fn main() -> std::io::Result<()> {
let mut first_name_table = HashMap::new();
let mut last_name_table = HashMap::new();

let person1 = Person { id: 1};
let first_name1 = "first1";
let last_name1 = "last1";

last_name_table.insert(last_name1, &person1);
first_name_table.insert(first_name1, person1);

let person2 = Person { id: 2};
let first_name2 = "first2";
let last_name2 = "last2";

last_name_table.insert(last_name2, &person2);
first_name_table.insert(first_name2, person2);

Ok(())
}
我得到的错误是:
error[E0505]: cannot move out of `person1` because it is borrowed
--> src/main.rs:20:42
|
19 | last_name_table.insert(last_name1, &person1);
| -------- borrow of `person1` occurs here
20 | first_name_table.insert(first_name1, person1);
| ^^^^^^^ move out of `person1` occurs here
...
26 | last_name_table.insert(last_name2, &person2);
| --------------- borrow later used here
但是第26行与 person1无关,那么为什么会发生这种情况?

最佳答案

当您将person1移至first_name_table时,会使存储在&person1中的引用last_name_table无效,但是如果您从不再次使用last_name_table,则编译器将使该代码编译,但是一旦您尝试使用last_name_table,该编译器将引发错误,因为它包含无效的引用。无论何时或尝试使用它,都没有关系。即使只是删除它也会触发错误:

use std::collections::HashMap;

struct Person { id: i32 }

fn main() -> std::io::Result<()> {
let mut first_name_table = HashMap::new();
let mut last_name_table = HashMap::new();

let person1 = Person { id: 1};
let first_name1 = "first1";
let last_name1 = "last1";

last_name_table.insert(last_name1, &person1);
first_name_table.insert(first_name1, person1);

drop(last_name_table); // triggers error

Ok(())
}

关于rust - Rust不能在hashmap中插入不同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66038087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com