Похожие чаты

Hi, I continue reading The Rust Programming Language book and

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?

6 ответов

22 просмотра

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

Pavel- Автор вопроса
dankey
you're redeclaring it at every iteration notice th...

Yes, but why I don't have to specify mut even though it's a mutable reference?

Pavel
Yes, but why I don't have to specify mut even thou...

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

Pavel- Автор вопроса
Artem Starikov
well, because in &mut i32 there's already a mut, s...

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")?

Pavel- Автор вопроса
Artem Starikov
yes

Got it, thanks!

Похожие вопросы

Обсуждают сегодня

а через ESC-код ?
Alexey Kulakov
29
30500 за редактор? )
Владимир
47
Чёт не понял, я ж правильной функцией воспользовался чтобы вывести отладочную информацию? но что-то она не ловится
notme
18
У меня есть функция где происходит это: write_bit(buffer, 1); write_bit(buffer, 0); write_bit(buffer, 1); write_bit(buffer, 1); write_bit(buffer, 1); w...
~
13
any reference of this implementation?
BitBuddha
29
Ⓐrtto, [4/23/24 7:02 PM] Please explain more fully how it is not working exactly, and what are the steps you are taking, and what error messages come or what happens. Ⓐrtto, ...
Ezza Kezza
2
sounds like people have lost their kaspa on tradeogre... does this mean tradeogre not trustworthy?
Ezza Kezza
15
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
So much speculation in the last week. So much volatility in price. This is because Hedera has a GC that isn't using the network it's governing. Why aren't people asking why a...
Summit Seeker R
9
Карта сайта