2

我想实现一个树数据结构。我有一个Node结构并希望它保存对 childNode的引用。我试过了:

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

我该如何实施?

4

1 回答 1

2

在这种情况下,实际上有必要查看编译器输出中的第二条错误消息:

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

变量在第 21 行node被移动hashmap 中。之后你就不能使用它了!在 Rust 中,我们有移动语义,这意味着默认情况下会移动所有内容,而不是默认情况下克隆 (C++) 或默认引用 (Java)。您想返回对哈希图Node对象的引用!

一种简单的方法是node像您已经在做的那样插入,然后从哈希图中获取值:

let mut node = Node::new(value);
self.children.insert(key.clone(), node);
self.children.get_mut(key).unwrap()

这应该清楚该函数的实际作用。但是,此代码有一些缺点:首先,我们必须克隆key(插入和查询都需要它),其次,hashmap 需要计算两次 key 的 hash,效率不高。

幸运的是,RustHashMap有一个不错的entry()-API。我们可以这样改变函数:

self.children.entry(key).or_insert_with(|| Node::new(value))

这是全身的add_child()!然而,现在我们注意到……我们还没有真正考虑过如果 hashmap 已经包含与给定键关联的值会发生什么!在上面的代码中,旧值被保留并返回。如果您想做其他事情(例如替换值),您可以matchEntry对象上使用:

let node = Node::new(value);
match self.children.entry(key) {
    Entry::Occupied(e) => {
        // Maybe you want to panic!() here... but we will just 
        // replace the value:
        e.insert(node);  // discarding old value...
        e.get_mut()
    }
    Entry::Vacant(e) => insert(node),
}
于 2017-04-02T18:32:18.223 回答