I wrote a "count all character occurrences in a string" function with Rust, but updating/adding to the values does not work with bracket notation. Why is that?
What works is this:
use std::collections::HashMap;
fn main() {
let myString = "Go ahead and count all my characters";
let mut myMap = HashMap::new();
for ch in myString.chars() {
*myMap.entry(ch).or_insert(0) += 1;
}
}
What does NOT work is:
for ch in myString.chars() {
myMap.entry(ch).or_insert(0);
*myMap[&ch] += 1;
}
In the latter case, the compiler complains:
error[E0614]: type `{integer}` cannot be dereferenced
--> src/main.rs:10:9
|
10 | *myMap[&ch] += 1;
| ^^^^^^^^^^^
This makes sense because they are copied and stored on the stack (if I understand correctly), but you also cannot add 1 to them if you do not try do dereference the value. It looks like the first version is the only option I have; is that correct? Why does it work there?