在 Rust 中添加或增加 HashMap 中的值

Sou*_*osh 2 hashmap rust

我是 Rust 新手,最近开始学习。我编写了一个简单的程序,它执行以下操作。

  1. 读取文本文件
  2. 分割单词并将它们及其出现次数存储在 HashMap 中
  3. 迭代地图并打印单词和出现次数
use std::io;
use std::env;
use std::collections::HashMap;
use std::fs;

fn main() {
    let path = env::args().nth(1).unwrap();
    let contents = read_file(path);
    let map = count_words(contents);
    print(map);
}

fn read_file(path: String) -> (String){
    let contents =  fs::read_to_string(path).unwrap();
    return contents;
}

fn count_words(contents: String) -> (HashMap<String, i32>){
    let split = contents.split(&[' ', '\n'][..]);
    let mut map = HashMap::new();
    for w in split{
        if map.get(w) == None{
            map.insert(w.to_owned(), 1);
        }
        let count = map.get(w);
        map.insert(w.to_owned(), count + 1); // error here
    }
    return map;
}

fn print(map: HashMap<String, i32>){
    println!("Occurences..");

    for (key, value) in map.iter() {
        println!("{key}: {value}");
    }
}
Run Code Online (Sandbox Code Playgroud)

我能够读取该文件并将单词添加到 HashMap 中并打印。但是,在尝试添加或增加时,出现以下错误。

错误[E0369]:无法添加{integer}Option<&{integer}> --> src\main.rs:27:40 | 27 | 27 map.insert(w.to_owned(), count + 1); | ----- ^ - {整数} |
| | 选项<&{整数}>

我知道这种方法应该适用于其他语言,如 Java、C# 等,但不确定它在 Rust 中应该如何工作。

Gre*_*ous 6

在这个块中:

if map.get(w) == None{
            map.insert(w.to_owned(), 1);
        }
        let count = map.get(w);
        map.insert(w.to_owned(), count + 1); // error here
Run Code Online (Sandbox Code Playgroud)

map.get(w)给你一个Option<w>文档);

你似乎在某种程度上知道这一点,当你检查它是否None更早时 - 另一种可能性是它是你想要的 - a Some(w)(不仅仅是w);

您不能将 an 添加int到 a Some,正如编译器告诉您的那样 - 您必须w从 中取出“the”(计数整数)Some


您可以unwrapdoc),尽管不建议这样做。


您可以使用模式匹配

match map.get(&w) {
    Some(count) => { map.insert(w, count + 1); }
    None => { map.insert(w, 1); }
}
Run Code Online (Sandbox Code Playgroud)

或者,换一种写法:

if let Some(count) = map.get(&w) {
    map.insert(w, count + 1);
} else {
    map.insert(w, 1);
};
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,您可以使用Entry API,它将其变成一个简单的单行:

    *map.entry(w.to_owned()).or_default() += 1;
Run Code Online (Sandbox Code Playgroud)