我想實現一個樹型數據結構。我有一個Node
結構,並希望它保存對子代Node
的引用。我想:實現樹型數據結構
use std::collections::*;
#[derive(Debug)]
struct Node {
value: String,
children: HashMap<String, Node>,
}
impl Node {
fn new(value: String) -> Self {
Node {
value: value,
children: HashMap::new(),
}
}
fn add_child(&mut self, key: String, value: String) -> &mut Node {
let mut node = Node::new(value);
self.children.insert(key, node);
&mut node
}
}
fn main() {
let mut root_node = Node::new("root".to_string());
root_node.add_child("child_1_1".to_string(), "child_1_1_value".to_string());
}
此代碼不能編譯:
error: `node` does not live long enough
--> src/main.rs:22:10
|
22 | &mut node
| ^^^^ does not live long enough
23 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 19:67...
--> src/main.rs:19:68
|
19 | fn add_child(&mut self, key: String, value: String) -> &mut Node {
| ____________________________________________________________________^ starting here...
20 | | let mut node = Node::new(value);
21 | | self.children.insert(key, node);
22 | | &mut node
23 | | }
| |___^ ...ending here
error[E0382]: use of moved value: `node`
--> src/main.rs:22:10
|
21 | self.children.insert(key, node);
| ---- value moved here
22 | &mut node
| ^^^^ value used here after move
|
= note: move occurs because `node` has type `Node`, which does not implement the `Copy` trait
我如何能實現呢?
的[有沒有辦法返回到一個函數創建一個變量的引用可能的重複? ](http://stackoverflow.com/q/32682876/155423) – Shepmaster
@Shepmaster可能不是。有多個問題,但OP想要將新創建的值插入到散列映射中,並返回對散列映射內部值的引用(請參閱第二個錯誤,在這種情況下更重要)。 –