【发布时间】:2020-09-30 03:29:19
【问题描述】:
我有几个状态要存储在各自的哈希图中。看起来像这样的东西:
let mut directory_hash: HashMap<String, String> = HashMap::new();
let mut component_hash: HashMap<String, String> = HashMap::new();
let mut directive_hash: HashMap<String, String> = HashMap::new();
我希望所有这些切片都保存在一个 app_state 对象中,我将像这样初始化它:
pub fn init_app_state() -> HashMap<&'static str, HashMap<String, String>> {
let mut directory_hash: HashMap<String, String> = HashMap::new();
let mut component_hash: HashMap<String, String> = HashMap::new();
let mut directive_hash: HashMap<String, String> = HashMap::new();
let mut tree_state: HashMap<&str, HashMap<String, String>> = HashMap::new();
tree_state.insert("directory_hash", directory_hash);
tree_state.insert("component_hash", component_hash);
tree_state.insert("module_hash", module_hash);
tree_state
}
let mut app_state = state::app_state::init_app_state();
现在假设我想插入其中一个嵌套的哈希图。我该怎么做?
以下是一些无效示例的 sn-p:
-
let mut app_state = state::app_state::init_app_state(); let mut dir_hash = &mut app_state["directory_hash"]; dir_hash.insert(String::from("1"), String::from("first entry"));上面的错误在第二行(app_state["directory_hash"])
cannot borrow data in an index of `std::collections::HashMap<&str, std::collections::HashMap<std::string::String, std::string::String>>` as mutable cannot borrow as mutable help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<&str, std::collections::HashMap<std::string::String, std::string::String>>`rustc(E0596) -
let mut app_state = state::app_state::init_app_state(); let mut dir_hash = &mut app_state.entry("directory_hash"); dir_hash.insert(String::from("1"), String::from("first entry"));这里的错误在第 3 行 (dir_hash.insert(.....))
use of unstable library feature 'entry_insert' note: see issue #65225 <https://github.com/rust-lang/rust/issues/65225> for more information我查看了entry API,但我不确定这是否是要采取的方法。
如何更新这个嵌套的状态?
我可能会将这些 HashMap 实例中的每一个更改为 State 结构上的属性。但我仍然对上述方法在 Rust 中的工作方式感到好奇。
这是我目前采用的方法:
pub struct State {
pub directory_hash: HashMap<String, String>,
pub component_hash: HashMap<String, String>,
pub module_hash: HashMap<String, String>,
}
impl State {
pub fn new() -> State {
let directory_hash: HashMap<String, String> = HashMap::new();
let component_hash: HashMap<String, String> = HashMap::new();
let module_hash: HashMap<String, String> = HashMap::new();
State {
directory_hash,
component_hash,
module_hash,
}
}
}
let app_state = state::app_state::State::new();
let mut dir_hash = app_state.directory_hash;
dir_hash.insert(String::from("1"), String::from("first value!"));
【问题讨论】:
标签: data-structures rust hashmap