该程序接受一个整数 N,后跟 N 行,其中包含由空格分隔的两个字符串。我想将这些行放入 aHashMap
中,使用第一个字符串作为键,第二个字符串作为值:
use std::collections::HashMap;
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("unable to read line");
let desc_num: u32 = match input.trim().parse() {
Ok(num) => num,
Err(_) => panic!("unable to parse")
};
let mut map = HashMap::<&str, &str>::new();
for _ in 0..desc_num {
input.clear();
io::stdin().read_line(&mut input)
.expect("unable to read line");
let data = input.split_whitespace().collect::<Vec<&str>>();
println!("{:?}", data);
// map.insert(data[0], data[1]);
}
}
该程序按预期工作:
3
a 1
["a", "1"]
b 2
["b", "2"]
c 3
["c", "3"]
当我尝试将这些解析的字符串放入 aHashMap
和 uncommentmap.insert(data[0], data[1]);
时,编译失败并出现以下错误:
error: cannot borrow `input` as mutable because it is also borrowed as immutable [E0502]
input.clear();
^~~~~
note: previous borrow of `input` occurs here; the immutable borrow prevents subsequent moves or mutable borrows of `input` until the borrow ends
let data = input.split_whitespace().collect::<Vec<&str>>();
^~~~~
note: previous borrow ends here
fn main() {
...
}
^
我不明白为什么会出现这个错误,因为我认为map.insert()
表达式根本没有借用字符串input
。