我在section 8.3 of The Book年为第三个提议的练习写了一个可行的解决方案,但其中一些行为违背了我的直觉.具体地说,我似乎能够改变一个似乎实例化为不可变的向量.
我已经包括了我认为相关的代码部分,省略了与HashMap
中存储的Vec
不交互的代码部分.
我在代码块之后进行了一些猜测,但我真的需要一个更可靠的解释来说明实际发生了什么.
// Start by declaring a new HashMap. This is where the mystery begins for me.
let mut departments: HashMap<String, Vec<String>> = HashMap::new();
// This code deals with getting user input from stdin and has been elided
// ...
// Match the first string slice
match args[0] {
// Add an employee to a department in the HashMap
"add" => {
// POINT OF INTEREST 1
// Adding a department that isn't already in the HashMap will cause a new empty
// vector to be inserted at the newly created key
let list = departments.entry(args[2].to_string()).or_insert(Vec::new());
// In any case, we insert the employee's name into the vector associated with
// whatever department we got from stdin
list.push(args[1].to_string());
}
// List employees
"who" => match args[1] {
// List all employees in every department, employees shown in alphabetical order
"all" => {
for (department, employees) in &mut departments {
// POINT OF INTEREST 2
// Why am I allowed to sort this vector? The artifact underlying the reference
// was never explicitly made mutable.
employees.sort();
for ee in employees {
println!("{}: {}", department, ee);
}
}
}
// List all employees in a given department, employees shown in alphabetical order
dept => {
let employees = departments.get_mut(dept);
match employees {
Some(entries) => {
// POINT OF INTEREST 3
// This one is seems the least mysterious to me, since I get the value
// of the HashMap at `dept` through `.get_mut()`.
println!("{}:", dept);
entries.sort();
for ee in entries {
println!("\t{}", ee);
}
}
_ => (),
}
}
}
}
Hypothesis 1:at POINT OF INTEREST 1
,我对.or_insert()
returns a mutable reference的调用是对一个新向量的调用,而this是后来对HashMap中值的.sort()
值进行调用的原因.
这看起来不像是可能的答案!在开始时,我声明departments
是类型HashMap<String, Vec<String>>
,not,HashMap<String, &mut Vec<String>>
.
Hypothesis 2:当我将departments
声明为可变时,它的键和值将继承这种可变性.这似乎不太可能,因为在我(非常有限的)经验中,没有任何东西表明这样的事情是铁 rust 的一个特征.我还认为,如果这本书的前8章明确说明了这一点,我就会注意到这一点,但我以前就知道会略过重要的细节.