【问题标题】:Taking ownership of HashMap.get() result without cloning在不克隆的情况下获得 HashMap.get() 结果的所有权
【发布时间】:2020-07-16 05:10:43
【问题描述】:

有没有比这行更有效的从 HashMap 获取拥有值的方法?

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

此屏幕截图扩展了类型:

【问题讨论】:

  • 你要从HashMap中取吗?

标签: rust


【解决方案1】:

如果您想获得该值的所有权,HashMap::remove() 将返回 Option<T>,而不是 HashMap::get() 返回的 Option<&T>。见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);
}

如果您希望该值保留在 HashMap 中,但同时在其他地方拥有该值,您可以将其包装在 Rc<T> 中以共享所有权。如果对象需要可变,可以将其包装在Rc<RefCell<T>> 中。

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2020-08-08
    • 2017-12-29
    • 2017-08-17
    • 2013-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多