I am trying to create a struct, which contains a hashmap and a vector, thereby the vector should contain references to values from the hashmap.
I thought that multiple mutable borrows on the same instance are possible, when put into independent scopes.
use std::collections::HashMap;
struct Container<'a> {
map: HashMap<String, String>,
vec: Vec<&'a String>
}
impl<'a> Container<'a> {
pub fn new() -> Self {
Container {
map: HashMap::new(),
vec: Vec::new()
}
}
pub fn add_link(&'a mut self, key: &str) {
if let Some(value) = self.map.get(key) {
self.vec.push(value);
}
}
pub fn print_vec(&self) {
println!("Vec: {:?}", self.vec);
}
}
fn main() {
let mut container = Container::new();
{
container.map.insert("a".to_string(), "x".to_string());
}
{
container.map.insert("b".to_string(), "y".to_string());
}
{
container.map.insert("c".to_string(), "z".to_string());
}
{
container.add_link("c");
}
{
container.add_link("a");
}
{
container.add_link("c");
}
{
container.add_link("k");
}
container.print_vec();
}
error[E0499]: cannot borrow `container` as mutable more than once at a time
--> src/main.rs:44:9
|
41 | container.add_link("c");
| --------- first mutable borrow occurs here
...
44 | container.add_link("a");
| ^^^^^^^^^
| |
| second mutable borrow occurs here
| first borrow later used here
(...)
I am expecting the output to be: Vec: ["z", "x", "z"]