【发布时间】:2020-07-10 16:30:31
【问题描述】:
我正在打开一个 CSV 文件并使用 BufReader 读取它并将每一行拆分为一个向量。然后我尝试使用特定列作为键在HashMap 中插入或更新计数。
let mut map: HashMap<&str, i32> = HashMap::new();
let reader = BufReader::new(input_file);
for line in reader.lines() {
let s = line.unwrap().to_string();
let tokens: Vec<&str> = s.split(&d).collect(); // <-- `s` does not live long enough
if tokens.len() > c {
println!("{}", tokens[c]);
let count = map.entry(tokens[c].to_string()).or_insert(0);
*count += 1;
}
}
编译器好心地告诉我s 是短暂的。 Storing from inside a loop a borrowed value to container in outer scope? 建议“拥有”字符串,所以我尝试更改
let count = map.entry(tokens[c]).or_insert(0);
到
let count = map.entry(tokens[c].to_string()).or_insert(0);
但我得到了错误
expected `&str`, found struct `std::string::String`
help: consider borrowing here: `&tokens[c].to_string()`
当我在 & 前面加上 (&) 时,错误是
creates a temporary which is freed while still in use
note: consider using a `let` binding to create a longer lived
我对借用的 Rust 知识有一些不足。如何让 hashmap 拥有作为键传递的字符串?
【问题讨论】:
-
你是如何声明
map的? -
谢谢,添加了地图声明。你解决了我的问题。我将声明更改为 HashMap
。我在 rust-lang.org 上使用了一个 hashmap-example,它使用了 &str. -
谢谢,我在我们说话的时候就这么做了。您可以将其添加为答案吗?
-
很难回答您的问题,因为它不包含minimal reproducible example。我们无法分辨代码中存在哪些 crate(及其版本)、类型、特征、字段等。如果您尝试在Rust Playground 上重现您的错误,如果可能的话,这将使我们更容易为您提供帮助,否则在全新的 Cargo 项目中,然后在edit 您的问题中包含附加信息。您可以使用Rust-specific MRE tips 来减少您在此处发布的原始代码。谢谢!
-
请edit 您的问题并粘贴您所遇到的确切和全部错误——这将有助于我们了解问题所在,以便我们提供最佳帮助。有时试图解释错误消息很棘手,实际上错误消息的不同部分很重要。请使用直接运行编译器的消息,而不是 IDE 生成的消息,它可能会尝试为您解释错误。
标签: for-loop rust hashmap ownership