rust - 使用 None 访问 Rust 中的嵌套 HashMap

标签 rust hashmap ownership

我想创建一个类似于 this post 中的数据结构。因此,数据库节点树包含与该节点关联的一些数据,以及更深层次的节点。

不同之处在于,我希望允许 childrenNone 的可能性,以指示该节点是叶子。

所以它应该看起来像:

{
  "1": Database {
    {
      data: "element 1",
      children: Some({
        "a": Database {
          data: "element 1-a",
          children: None
        },
        "b": Database {
          data: "element 1-b",
          children: None
        }
      })
    }
  },
  "2": Database {
    {
      data: "element 2",
      children: None
    }
  }
}

使用the original post中的代码,我想出了这个[ playground link ]:

#[derive(Default, Debug)]
struct Database {
    children: Option<HashMap<String, Database>>,
    data: String,
}

impl Database {
    fn insert_path(&mut self, path: &[&str]) -> &mut Self {
        let mut node = self;
        for &subkey in path.iter() {
            if let None = node.children {
                node.children = Some(HashMap::new());
            }
            node = node
                .children
                .unwrap()
                .entry(subkey.to_string())
                .or_insert_with(Database::default);
        }
        node
    }
}

fn main() {
    let mut db = Database {
        children: Some(HashMap::new()),
        data: "root".to_string(),
    };

    let node = db.insert_path(&vec!["key1", "key1.1", "key1.1.3"]);
    node.data = "myvalue".to_string();

    println!("{:#?}", db);
}

这行不通。我收到以下错误:

error[E0507]: cannot move out of `node.children` which is behind a mutable reference
  --> src/main.rs:18:20
   |
18 |               node = node
   |  ____________________^
19 | |                 .children
   | |_________________________^ move occurs because `node.children` has type `Option<HashMap<String, Database>>`, which does not implement the `Copy` trait
   |
help: consider borrowing the `Option`'s content
   |
18 |             node = node
19 |                 .children.as_ref()
   |

error[E0515]: cannot return value referencing temporary value
  --> src/main.rs:24:9
   |
18 |               node = node
   |  ____________________-
19 | |                 .children
20 | |                 .unwrap()
   | |_________________________- temporary value created here
...
24 |           node
   |           ^^^^ returns a value referencing data owned by the current function

我很困惑为什么会发生这种情况。我认为在 node.children 上使用 unwrap() 会删除移动的值 node.children。但是,我不知道如何在不使用 unwrap() 的情况下执行此操作。我如何才能通过使用 None 的新结构实现原始帖子的功能?这可能吗?

注意:我还删掉了原来的代码,以便它与上面的代码更相似并且更容易比较。请参阅here Playground 链接。

最佳答案

如果添加 as_mut(),则您的示例将编译之后children ,即:

node = node
    .children
    .as_mut()
    .unwrap()
    .entry(subkey.to_string())
    .or_insert_with(Database::default);

Option::as_mut变成Option<T>进入Option<&mut T> ,从而防止移出 node当你 unwrap() node.children .

关于rust - 使用 None 访问 Rust 中的嵌套 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67255274/

相关文章:

multidimensional-array - 如何在不复制的情况下将 ndarray::ArrayView 转换为 &ndarray::Array?

java - HashMap 中的值被新值覆盖 (Java)

generics - 编译器如何推断Box正在借用其内容借来的那个?

rust - 在 &mut self 方法中展开成员变量时无法移出借用的内容

c++ - 返回 C++ 多态对象(接口(interface))

rust - 在字符串上创建闭包返回迭代器

logging - 如何在warp中记录请求/响应主体?

rust - Iterator vs IntoIterator 用于扁平化

java - 在 SimpleXML 中序列化/反序列化 Java HashMap

java - 如何声明最终的 HashMap 不允许更新或删除元素