max
max

Reputation: 529

Taking ownership of HashMap.get() result without cloning

Is there a more efficient way of getting an owned value from a HashMap than this line?

let output_items = output_tables.get(TABLE_NAME_TLIST).unwrap().to_owned();

This screenshot expands the types:

code snippet

Upvotes: 8

Views: 3810

Answers (1)

Mac O'Brien
Mac O'Brien

Reputation: 2907

If you want to take ownership of the value, HashMap::remove() will return an Option<T> rather than the Option<&T> returned by HashMap::get(). See this playground:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "a");
    assert_eq!(map.remove(&1), Some("a"));
    assert_eq!(map.remove(&1), None);
}

If you want the value to remain in the HashMap but also own the value elsewhere, you can wrap it in an Rc<T> to share ownership. If the object needs to be mutable, you can wrap it in an Rc<RefCell<T>>.

Upvotes: 17

Related Questions