0

Here is a piece of code that counts the frequency of words in a sentence.
I'm wondering if the HashMap can be set as immutable after counting the items.

let mut map = HashMap::new();
for word in s.split_whitespace() {
    *map.entry(word).or_insert(0) += 1;
}
// after the for loop make map immutable

I'm aware of the crate Counter with the collect API but I'd prefer to do it without crates.

I would also prefer a solution that doesn't use functions or closures.

  • Relevant questions: [What are move semantics in Rust?](https://stackoverflow.com/questions/30288782/what-are-move-semantics-in-rust), [What's the difference between placing "mut" before a variable name and after the ":"?](https://stackoverflow.com/questions/28587698/whats-the-difference-between-placing-mut-before-a-variable-name-and-after-the). – E_net4 Oct 20 '22 at 09:49

3 Answers3

1

In addition to Aleksander's answer, you can use Iterator::fold() to avoid making it mutable in the first place:

let map = s.split_whitespace().fold(HashMap::new(), |mut map, word| {
    *map.entry(word).or_insert(0) += 1;
    map
});
user4815162342
  • 141,790
  • 18
  • 296
  • 355
0

If you have a mutable variable and want to make it immutable later you can do simple shadowing:

// x is mut
let mut x = ...;

// do stuff with mut x

// now x is no longer mutable
let x = x;
Aleksander Krauze
  • 3,115
  • 7
  • 18
  • 1
    However note that there is no way to make it _truly_ immutable: it is always possible to shadow it back to be mutable: `let mut x = x;` – Jmb Oct 20 '22 at 10:25
  • 1
    @Jmb isn't that the same for every variable? – tglaria Oct 20 '22 at 12:56
0

If you want to make data truly unchangeable, e.g. to be sure it stays valid in between function calls, you can wrap the value in a newtype which implements the Deref-Trait. see playground

Now you can pass it around in your Application and rely, that all code which can change the inner value must be in the sealed module. If you find this interesting, you might want to check out my experimental crate sealedstruct for inspiration to generate boilerplate. Be aware that it is neither published nor well documented yet.

mineichen
  • 470
  • 2
  • 11