简体   繁体   English

有什么方法可以在 Rust 中一次将多个条目插入到 HashMap 中?

[英]Is there any way to insert multiple entries into a HashMap at once in Rust?

Is there any way to insert multiple entries into a HashMap at once in Rust?有什么方法可以在 Rust 中一次将多个条目插入到 HashMap 中? Or to initialize it with multiple entries?或者用多个条目初始化它? Anything other than manually calling insert on every single element you're inserting?除了在您要插入的每个元素上手动调用insert之外还有什么?

Edit for an example using English letter frequencies:使用英文字母频率编辑示例:

I basically want:我基本上想要:

let frequencies = { 
  'a': 0.08167, 
  'b': 0.01492, 
  ... 
  'z': 0.00074 
}

I know I can achieve the same result by doing a for loop like the following, but I want to know if there is a way to do this without creating additional arrays and then looping over them, or a more elegant solution in general.我知道我可以通过执行如下所示的 for 循环来获得相同的结果,但我想知道是否有一种方法可以在不创建额外数组然后循环遍历它们的情况下执行此操作,或者通常有更优雅的解决方案。

let mut frequencies = HashMap::new();
let letters = ['a','b','c', ...... 'z'];
let freqs = [0.08167, 0.01492, 0.02782, ......., 0.00074];
for i in 0..26 {
    frequencies.insert(letters[i], freqs[i]);
}

For a literal, I could use the answer here , which will probably work fine for this example, but I'm curious whether there's a way to do this without it being a literal, in case this comes up in the future.对于文字,我可以使用此处的答案,这对于这个示例可能会很好地工作,但我很好奇是否有一种方法可以在不使用文字的情况下执行此操作,以防将来出现这种情况。

Is there any way to insert multiple entries into a HashMap at once in Rust? 有没有办法在Rust中一次将多个条目插入HashMap?

Yes, you can extend a HashMap with values from an Iterator , like this: 是的,您可以使用Iteratorextend HashMap ,如下所示:

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.extend((1..3).map(|n| (format!("{}*2=", n), n * 2)));
    map.extend((7..9).map(|n| (format!("{}*2=", n), n * 2)));
    println!("{:?}", map); // Prints {"1*2=": 2, "8*2=": 16, "7*2=": 14, "2*2=": 4}.
}

It is even a bit faster than calling the insert manually, because extend uses the size hint provided by the Iterator in order to reserve some space beforehand. 它甚至比手动调用insert快一点,因为extend使用Iterator提供的大小提示来预先保留一些空间。

Check out the source code of the method here, in map.rs . 在map.rs中查看方法的源代码。

Or to initialize it with multiple entries? 或者用多个条目初始化它?

This is possible as well, thanks to HashMap implementing the FromIterator trait. 这也是可能的,这要归功于HashMap实现了FromIterator特性。 When a collection implements FromIterator , you can use the Iterator::collect shorthand to construct it. 当集合实现FromIterator ,您可以使用Iterator::collect简写来构造它。 Consider the following examples, all of them generating the same map: 考虑以下示例,所有这些示例都生成相同的映射:

use std::collections::HashMap;

fn main() {
    let mut map: HashMap<_, _> = (1..3).map(|n| (format!("{}*2=", n), n * 2)).collect();
    map.extend((7..9).map(|n| (format!("{}*2=", n), n * 2)));
    println!("{:?}", map); // Prints {"1*2=": 2, "8*2=": 16, "7*2=": 14, "2*2=": 4}.
}

use std::collections::HashMap;

fn main() {
    let map: HashMap<_, _> = (1..3)
        .chain(7..9)
        .map(|n| (format!("{}*2=", n), n * 2))
        .collect();
    println!("{:?}", map); // Prints {"1*2=": 2, "8*2=": 16, "7*2=": 14, "2*2=": 4}.
}

use std::collections::HashMap;
use std::iter::FromIterator;

fn main() {
    let iter = (1..3).chain(7..9).map(|n| (format!("{}*2=", n), n * 2));
    let map = HashMap::<String, u32>::from_iter(iter);
    println!("{:?}", map); // Prints {"1*2=": 2, "8*2=": 16, "7*2=": 14, "2*2=": 4}.
}
use std::collections::HashMap;

fn main() {

    // Insert multiple entries into a HashMap at once
    let mut map = HashMap::new();
    let pairs = [
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("z", 50),
    ];
    map.extend(pairs);
    println!("map: {map:#?}\n");
    
    // Initialize with multiple entries
    let map = HashMap::from([
        ("a", 1),
        ("b", 2),
        ("c", 3),
        ("z", 50),
    ]);
    println!("map: {map:#?}\n");
}

See the Rust Playground .请参阅Rust 游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM