I have a file key/value:
key1,valueA
key1,valueB
key2,valueC
..
..
And I've to store the file in a HashMap<&str, Vec<&str>>, the above file becomes:
["key1 -> vec![valueA,valueB]]
["key2 -> vec![valueC]]
..
..
My code reads a single line from the file, search in the hashmap and if the key exists, then it adds the value to the list, otherwise it creates a new element in a hashmap with the key and vec[value]
let mut rows:HashMap<&str, Vec<&str>> = HashMap::new();
let file = File::open(file_in).unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let a = line.unwrap().split(",").collect::<Vec<&str>>();
// a[0] -> key
// a[1] -> value
match rows.get_mut(&a[0]) {
Some(stored_row) => {
stored_row.push(a[1]);
}
None => {
rows.insert(&a[0], vec![a[1]]);
}
}
}
The error is:
error[E0716]: temporary value dropped while borrowed
|
28 | let a = line.unwrap().split(",").collect::<Vec<&str>>();
| ^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
...
31 | match rows.get_mut(&a[0]) {
| - borrow later used here
|
= note: consider using a `let` binding to create a longer lived value