Re-Binding Variable in a Loop

I'm trying to construct a multipart body for a POST request using the reqwest library. If I knew all of the fields ahead of time, I can simply call form.text("key", "value") numerous times; however, I don't. I'm trying to loop over a HashMap and insert these pairs:

    let mut form = reqwest::multipart::Form::new();

    for (k,v) in fields.into_iter() {
        let mut form = form.text(k, v);
    }

However, I get the following error:

error[E0382]: use of moved value: `form`
  --> src/main.rs:75:24
   |
72 |     let mut form = reqwest::multipart::Form::new();
   |         -------- move occurs because `form` has type `reqwest::multipart::Form`, which does not implement the `Copy` trait
...
75 |         let mut form = form.text(k, v);
   |                        ^^^^ value moved here, in previous iteration of loop

To get around the use-after-move, I tried inserting clone(); however, that's not implemented for Form. So is there any way to programatically add these key/value pairs?

Change this to form = ..., you are accidentally shadowing the original form binding.

1 Like

@RustyYato, thanks for the quick reply, sorry for the long delay in my reply.

Removing the let as you suggested fixed my problem... but I'm not exactly sure why. I created this quick playground to test: Rust Playground

struct Thing { }

impl Thing {
    pub fn consume(self) -> Thing {
        Thing {}
    }
}

fn main() {
    let a = Thing { };
    
    let a = a.consume();
    let a = a.consume();
    
    
    let b = Thing {};
    
    for _ in 0..2 {
        let b = b.consume();
    }
}

The non-loop code, and the loop code should do exactly the same thing, but only the non-loop one complies... why?

The "unrolled" equivalent of a loop would actually look like this:

    let a = Thing { };
    
    { // iteration 1
        let a = a.consume();
    }
    { // iteration 2
        let a = a.consume();
    }

each iteration creates its own variable, not visible to the iterations to come.

@krdln, ahhh... gotcha. So the "new a" isn't in scope for iteration 2, but "old a" which is has already been consumed. Thanks for the clarification!

1 Like

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