Похожие чаты

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 ответов

28 просмотров

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!

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

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

Господа, а что сейчас вообще с рынком труда на делфи происходит? Какова ситуация?
Rꙮman Yankꙮvsky
29
А вообще, что может смущать в самой Julia - бы сказал, что нет единого стандартного подхода по многим моментам, поэтому многое выглядит как "хаки" и произвол. Короче говоря, с...
Viktor G.
2
@Benzenoid can you tell me the easiest, and safest way to bu.y HEX now?
Živa Žena
20
This is a question from my wife who make a fortune with memes 😂😂 About the Migration and Tokens: 1. How will the old tokens be migrated to the new $LGCYX network? What is th...
🍿 °anton°
2
30500 за редактор? )
Владимир
47
а через ESC-код ?
Alexey Kulakov
29
What is the Dex situation? Agora team started with the Pnetwork for their dex which helped them both with integration. It’s completed but as you can see from the Pnetwork ann...
Ben
1
Гайс, вопрос для разносторонее развитых: читаю стрим с юарта, нада выделять с него фреймы с определенной структурой, если ли чо готовое, или долбаться с ринг буффером? нада у...
Vitaly
9
Anyone knows where there are some instructions or discort about failed bridge transactions ?
Jochem
21
@lozuk how do I get my phex copies of my ehex from a atomic wallet, to move to my rabby?
Justfrontin 👀
11
Карта сайта