Git repo: https://github.com/caveofprogramming/rust
Basic Map Usage
Here I create a map, insert key-value pairs into it, and print it.
This map doesn’t look strongly typed, but it is. After this I have to insert &str
for keys and i32 for values.
The types seem to be inferred on the first insert!
Looping over the map entries is also easy
Retrieving Values from Maps
Well, here is where the pain starts. Rust is very insistent on not letting me do anything stupid.
When I retrieve a value from a map with get()
, I get an option. I can print that with copied()
and unwrap_or()
.
Rust forces me to handle the possibility of the key not existing in the map.
I could also deal with the Option
using if let
, or match
.
Inserting Entries
If I insert entries into the map, by default the values overwrite any existing entry with the same key that already exists.
Bob is now 48.
I can use or_insert()
to insert values only if the key does not already exist in the map.
Bob is unaffected but Ethel has been added.
Modifying Entries Based on Existing Values
Here is one way I can modify an entry based on its existing value.
Bob is 148 now.
What are the pipes |age|
for? No idea. Some kind of lambda expression? I guess we’ll cover it later.
Here’s another way that seems simpler. We get a reference to Ethel’s age, but we’re forced to decide what to return if she doesn’t exist.
Then we can dereference the reference with *
and update her age.
Now Ethel is 42, not 22. Happens to us all.
Maps Insert Moves Things That Don’t Implement the Copy Trait
I suppose this isn’t really map-specific, but when we pass mutable strings to insert
, ownership is transferred, so the original strings become invalid.
If I uncomment the println!
lines in this code, it no longer works, because the key
and value
strings are no longer valid after passing them to insert
.