Rust ownership and borrowing
Rust Ownership and Borrowing Practice with HashMap and Vec
Rust has a unique approach to memory management called ownership and borrowing. In Rust, every value has an owner, which is responsible for managing the memory used by the value. When a value goes out of scope, its memory is automatically freed. Let's use a example to practice Rust's ownership and borrowing.
Problem Description
Given two strings ransomNote
and magazine
, return true if ransomNote
can be constructed from magazine
and false otherwise. Each letter in magazine
can only be used once in ransomNote
.
Example 1
Example 2
Example 3
Constraints
1 <= ransomNote.length, magazine.length <= 10^5
ransomNote
andmagazine
consist of lowercase English letters.
Solutions
According to the problem above, we want to use a container to store the characters in magazine
and check if the characters in randsomNote
are in the container. There are some collection types to store and retrieve data in rust, like:
Sequence:
Vec
,String
,VecDeque
,LinkedList
Maps:
HashMap
,BTreeMap
Sets:
HashSet
,BTreeSet
Misc:
BinaryHeap
Solution with Vec
So, here we can use a Vec
to store the characters in magazine
. The vec
type is a resizable array that stores values in contiguous memory blocks. And some important features of a Vec
are:
A
Vec
can grow or shrink at runtime.Values in a
Vec
can also be fetched using a reference to the collection.
Here is a more concise way to do this:
Solution with HashMap
We can also use a HashMap
to store the characters in magazine
. The HashMap
type is a collection of key-value pairs. And some important features of a HashMap
are:
A
HashMap
can grow or shrink at runtime.
Because we will meet the same character in ransomNote
, we can use the character as the key and the number of the character as the value. So, we can use a HashMap<char, i32>
to store the characters in magazine
. And we can use the entry()
method to check if the key is in the HashMap
and update the value.
Here is a more concise way to do this:
Conclusion
In my opinion, we do not need to scare the ownership and borrowing. We just need to know that we can use &
to borrow a reference to the value and use &mut
to borrow a mutable reference to the value. And we can use &
and &mut
to pass the value to a function etc. *
to dereference a reference. In another word, it is to get the value from a reference. And we can use *
to get the value from a mutable reference and change the value.
Last updated
Was this helpful?