我正在尝试在rust中建立对象/结构的哈希表...但是我不明白这个具体问题(生命周期错误)。
#[derive(Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
identifier: &'a str,
sha_id: Vec<u8>,
successor_id: Option<Vec<u8>>,
predecessor_id: Option<Vec<u8>>,
}
impl<'a> Node<'a> {
...
..
.
}
pub struct Application<'a> {
hash_map: HashMap<&'a str, Node>,
}
impl<'a> Application<'a> {
fn join(&self, node: &Node) {
self.hash_map.insert(node.identifier, node);
}
}
该错误是hash_map: HashMap<&'a str, Node>
中缺少的生存期说明符,我试图解决将Node更改为Node <'a>的问题,但是当我尝试插入时会引发“类型不匹配”错误。
我也不是为什么我会错过这个问题,而我找不到解决办法。
更新:
#[derive(Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
identifier: &'a str,
sha_id: Vec<u8>,
successor_id: Option<Vec<u8>>,
predecessor_id: Option<Vec<u8>>,
}
impl<'a> Node<'a> {
...
..
.
}
pub struct Application<'a> {
hash_map: HashMap<&'a str, Node<'a>>,
}
impl<'a> Application<'a> {
fn join(&self, node: &Node) {
self.hash_map.insert(node.identifier, *node);
}
}
输出为:
"explicit lifetime required in the type of `node`"
UPDATE2:
pub struct Application<'a> {
hash_map: HashMap<&'a str, Node<'a>>,
}
impl<'a> Application<'a> {
fn join(&mut self, node: &'a Node<'a>) {
self.hash_map.insert(node.identifier, *node);
}
}
输出为:
self.hash_map.insert(node.identifier, *node); cannot move out of borrowed content
完整解决方案
#[derive(Clone, Hash, Eq, PartialEq)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Node<'a> {
identifier: &'a str,
sha_id: Vec<u8>,
successor_id: Option<Vec<u8>>,
predecessor_id: Option<Vec<u8>>,
}
impl<'a> Node<'a> {
...
..
.
}
pub struct Application<'a> {
hash_map: HashMap<&'a str, Node<'a>>,
}
impl<'a> Application<'a> {
fn join(&mut self, node: Node<'a>) {
self.hash_map.insert(node.identifier, node);
}
}
答案 0 :(得分:0)
这个简化的示例似乎有用:
use std::collections::HashMap;
#[derive(Clone)] // we'll be cloning it later on
struct Node<'a> {
data: &'a i32
}
struct Test<'a> {
hash_map: HashMap<&'a str, Node<'a>> // the hash map owns the struct
}
impl<'a> Test<'a> {
fn new() -> Test<'a> {
Test {hash_map: HashMap::new()}
}
fn join(
&mut self, // must be mutable
node: Node<'a>) { // do not pass a reference
self.hash_map.insert("test", node); // inserting moves `node`
}
}
fn main() {
let stuff = Node {data: &12};
let mut test = Test::new();
test.join(stuff.clone()); // if we don't clone, `stuff` will get moved
println!("{}", *test.hash_map["test"].data); // outputs "12"
}
由于std::collections::HashMap::insert
试图移动其第二个参数,因此不能取消引用某个对象的指针并将其传递给此方法,因为否则该指针将变为未初始化的状态,这是不允许的。解决此问题的一种方法是传递移动的值而不是指向join
的指针。