it shows the next code as an example:
use std::collections::HashMap;
let text = "hello world wonderful world";
let mut map = HashMap::new();
for word in text.split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{:?}", map);
in this code we iterate over words from a string, create items in a hash map and increment their values.
As I understand count is a mutable reference, but it isn't marked as mut here and still this code works. What is the rule that allows to do this? Is it because map is mutable?
you're redeclaring it at every iteration notice the use of let inside the for loop you declare count, set it to the map entry, then dereference and increment that entry by one
Yes, but why I don't have to specify mut even though it's a mutable reference?
well, because in &mut i32 there's already a mut, so you don't need to specify count as mut. if you were to assign a different mutable reference to count, you would need count to be mut
Ah, so the type of count is something like "non-mutable reference to mutable i32" (by analogy to C "const pointer to non-const int")?
Got it, thanks!
Обсуждают сегодня