我想创建一个类似于 this post 中的数据结构。因此,数据库节点树包含与该节点关联的一些数据,以及更深层次的节点。
不同之处在于,我希望允许 children
为 None
的可能性,以指示该节点是叶子。
所以它应该看起来像:
{
"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/