Updating a Hashmap inside for loop

I have a Hashmap which I am trying to update inside the for loop, based on if else statement.

fn makemethdb(file: &String) {
    let bed = File::open(file).expect("Can not!");
    let bedbuf = BufReader::new(bed);

    let mut methmap: HashMap<String, String> = HashMap::new();
    let mut chr: String = String::new();

    for line in bedbuf.lines(){
        let line = line.unwrap();
        let linespl: Vec<&str> = line.split('\t').collect();
        let mut linechr: String = linespl[0].to_owned().to_string();
        let mut linestart: String = linespl[1].to_owned().to_string();
        let mut mval: String = linespl[2].to_owned().to_string();   

        if chr.is_empty(){
            let chr = linechr;
            methmap.insert(linestart, mval);
        }else {
            if chr == linechr{
                methmap.insert(linestart, mval);
                let mutmethmap: HashMap<String, String> = HashMap::new();
                let chr = linechr;
                methmap.insert(linestart, mval);

I am getting value borrowed here after move error at first occurance of methmap inside for loop. How do I resolve the issue?
I apologize is advance, I am quite new to the language.


First, a few quick tips: you can remove a lot of the type annotations and let the compiler infer the types for you. And you can use https://play.rust-lang.org/ to do simple tests and share code snippets. It is also helpful to provide the full error message.

When I copy-paste that code snippet into the playground, there is no error (including the necessary use statements) but there are a lot of warnings showing that you are creating variable bindings that are unused. I'm guessing this is not actually the same code that you are having problems with?


The code seems to compile, although the use of to_string after to_owned is redundant (type is already owned, why clone it again?) and all cases of the if will insert (linestart, mval) into methmap.


Hello both,

Thanks for the reply. I have updated a reproducible code on playground (I hope my code is readable enough).

Could you please suggest me how to circumvent the issue?

Change the existing variables instead of shadowing them with a new variable.

 } else {
     methdb.insert(chr.clone(), methmap);
-    let mut methmap: HashMap<String, String> = HashMap::new();
-    let chr = linechr;
+    methmap = HashMap::new();
+    chr = linechr;
     methmap.insert(linestart, mval);


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.