其他分享
首页 > 其他分享> > 【Rust】哈希映射(四)

【Rust】哈希映射(四)

作者:互联网

环境

示例

get_mut

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    if let Some(v) = map.get_mut("c") {
        *v += 3
    }
    println!("{:?}", map.get("c"));
}

insert

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.insert("d", 4);
    println!("{:?}", map);
}

remove

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.remove("b");
    println!("{:?}", map);
}

remove_entry

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    let entry = map.remove_entry("b");
    println!("{:?}", entry);
}

or_insert

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.entry("d").or_insert(4);
    println!("{:?}", map);
}

or_insert_with

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.entry("d").or_insert_with(|| 4);
    println!("{:?}", map);
}

or_insert_with_key

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.entry("d").or_insert_with_key(|k| k.len());
    println!("{:?}", map);
}

and_modify

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.entry("a").and_modify(|k| *k += 4);
    println!("{:?}", map);
}

or_default

fn main() {
    let mut map = HashMap::from([("a", 1), ("b", 2), ("c", 3)]);
    map.entry("d").or_default();
    println!("{:?}", map);
}

总结

了解了哈希映射中相关的一些方法。

附录

标签:map,HashMap,映射,mut,let,fn,哈希,main,Rust
来源: https://www.cnblogs.com/jiangbo4444/p/16322823.html