Skip to content

Commit

Permalink
Update collections.md - simplified entry API example (#140)
Browse files Browse the repository at this point in the history
Simplify the entry API example, as the `&'static str` doesn't add value here, and the entry API isn't actually very useful when you have non-Copy owned keys (like `String`) because you are forced to heap-allocate the String even if the key already exists.
  • Loading branch information
jonathanpallant authored Feb 28, 2024
1 parent 23b4852 commit 99da0e6
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions training-slides/src/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,18 +313,18 @@ fn entry(&mut self, key: K) -> Entry<K, V> {

```rust []
use std::collections::HashMap;

fn award_points(name: &'static str, map: &mut HashMap<String, u64>) {
map.entry(name.to_string())
.and_modify(|v| *v += 1)
fn update_connection(map: &mut HashMap<i32, u64>, id: i32) {
map.entry(id)
.and_modify(|v| *v = *v + 1)
.or_insert(1);
}

fn main() {
let mut map = HashMap::new();
award_points("Sam", &mut map);
award_points("Bob", &mut map);
award_points("Sam", &mut map);
update_connection(&mut map, 100);
update_connection(&mut map, 200);
update_connection(&mut map, 100);
println!("{:?}", map);
}
```
Expand Down

0 comments on commit 99da0e6

Please sign in to comment.