3

このプログラムは、整数 N を受け入れ、その後にスペースで区切られた 2 つの文字列を含む N 行が続きます。HashMap最初の文字列をキーとして、2 番目の文字列を値として使用して、これらの行を に入れたいと思います。

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"]

HashMapこれらの解析された文字列を aおよび uncommentに入れようとするとmap.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

4

1 に答える 1