This repository was archived by the owner on Jan 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
This repository was archived by the owner on Jan 18, 2025. It is now read-only.
Make get/get_mut/remove in HashMap more flexible with Borrow trait #12
Copy link
Copy link
Closed
Description
I noticed the TODO message along with the helpful hints in the HashMap implementation:
rust-algorithm-club/src/collections/hash_map/mod.rs
Lines 61 to 86 in 188bb59
/// Gets a reference to the value under the specified key. | |
/// | |
/// TODO: To treat owned and borrowed values in equivalent ways as other | |
/// collections in std do, we should use `Borrow` trait to abstract over | |
/// the type of key to hash. This concept can also applied for `get_mut` | |
/// `remove`, and other operations that constrain by the type system. | |
/// | |
/// Some useful resources: | |
/// | |
/// - [Trait std::borrow:Borrow][1] | |
/// - [TRPL 1st edition: Borrow and AsRef][2] | |
/// | |
/// # Complexity | |
/// | |
/// Constant (amortized). | |
/// | |
/// [1]: https://doc.rust-lang.org/stable/std/borrow/trait.Borrow.html | |
/// [2]: https://doc.rust-lang.org/stable/book/first-edition/borrow-and-asref.html | |
pub fn get(&self, key: &K) -> Option<&V> { | |
let index = self.make_hash(key); | |
self.buckets.get(index).and_then(|bucket| | |
bucket.iter() | |
.find(|(k, _)| *k == *key) | |
.map(|(_, v)| v) | |
) | |
} |
if it's not currently under development, I would love to give it a try!
weihanglo
Metadata
Metadata
Assignees
Labels
No labels