update HashMap.md

This commit is contained in:
sunface
2022-03-08 15:48:10 +08:00
parent c38f124a31
commit 009f6ac52e
2 changed files with 202 additions and 2 deletions

View File

@ -70,4 +70,93 @@ fn main() {
println!("Success!")
}
```
3.
```rust
// FILL in the blanks
use std::collections::HashMap;
fn main() {
// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, u8>` in this example).
let mut player_stats = HashMap::new();
// insert a key only if it doesn't already exist
player_stats.entry("health").or_insert(100);
assert_eq!(player_stats["health"], 100);
// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry("health").or_insert_with(random_stat_buff);
assert_eq!(player_stats["health"], 100);
// Ensures a value is in the entry by inserting the default if empty, and returns
// a mutable reference to the value in the entry.
let health = player_stats.entry("health").or_insert(50);
assert_eq!(health, &100);
*health -= 50;
assert_eq!(*health, 50);
println!("Success!")
}
fn random_stat_buff() -> u8 {
// could actually return some random value here - let's just return
// some fixed value for now
42
}
```
4.
```rust
use std::collections::HashMap;
#[derive(Hash, Eq, PartialEq, Debug)]
struct Viking {
name: String,
country: String,
}
impl Viking {
/// Creates a new Viking.
fn new(name: &str, country: &str) -> Viking {
Viking {
name: name.to_string(),
country: country.to_string(),
}
}
}
fn main() {
// Use a HashMap to store the vikings' health points.
let vikings = HashMap::from([
(Viking::new("Einar", "Norway"), 25),
(Viking::new("Olaf", "Denmark"), 24),
(Viking::new("Harald", "Iceland"), 12),
]);
// Use derived implementation to print the status of the vikings.
for (viking, health) in &vikings {
println!("{:?} has {} hp", viking, health);
}
}
```
5.
```rust
use std::collections::HashMap;
fn main() {
let v1 = 10;
let mut m1 = HashMap::new();
m1.insert(v1, v1);
println!("v1 is still usable after inserting to hashmap : {}", v1);
// &str implements Copy trait
let v2 = "hello";
let mut m2 = HashMap::new();
m2.insert(v2, v1);
assert_eq!(v2, "hello");
}
```