這應該是任何語言的一項簡單任務。這不適用於Rust。如何遍歷Hashmap,打印鍵/值並刪除Rust中的值?
use std::collections::HashMap;
fn do_it(map: &mut HashMap<String, String>) {
for (key, value) in map {
println!("{}/{}", key, value);
map.remove(key);
}
}
fn main() {}
這裏的編譯器錯誤:
error[E0382]: use of moved value: `*map`
--> src/main.rs:6:9
|
4 | for (key, value) in map {
| --- value moved here
5 | println!("{}/{}", key, value);
6 | map.remove(key);
| ^^^ value used here after move
|
= note: move occurs because `map` has type `&mut std::collections::HashMap<std::string::String, std::string::String>`, which does not implement the `Copy` trait
爲什麼它試圖移動的參考?從文檔中,我不認爲移動/借用適用於參考。
我可以通過映射{}中的for(key,value)得到同樣的錯誤;對於map {}中的(鍵,值),我不認爲這個答案解釋了這一點。 –
想一想,如果你在循環中調用'map.clear()'會發生什麼? 'key'和'value'是引用,它們不會再引用任何東西。 'clear'和'remove'都使用'&mut self',從借用檢查器的角度來看,它們是相同的。 – loganfsmyth
這使我碰到了一個偶然的問題,但我懷疑方法調用語法掩蓋了這個問題。 https://play.rust-lang.org/?gist=ecf6d9bdbe8e1ad99e5fb3c35c402d1c&version=stable –