Immutable borrow occurs

So here is my code (and yes I know the rust playground cant use curl) but I am getting the error

     |     println!("{:?}", dst);
     |                      ^^^ immutable borrow occurs here

and I have no idea how to fix this

The full error is as follows:

error[E0502]: cannot borrow `dst` as immutable because it is also borrowed as mutable
  --> src/main.rs:14:22
   |
9  |     transfer.write_function(|data| {
   |                             ------ mutable borrow occurs here
10 |         dst.extend_from_slice(data);
   |         --- first borrow occurs due to use of `dst` in closure
...
14 |     println!("{:?}", dst);
   |                      ^^^ immutable borrow occurs here
15 | }
   | - mutable borrow might be used here, when `transfer` is dropped and runs the `Drop` code for type `Transfer`

The problem is that transfer is holding a mutable reference to dst. You have to destroy transfer so it stops holding that mutable reference to access dst.

use curl::easy::Easy;

fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    let mut transfer = easy.transfer();
    transfer
        .write_function(|data| {
            dst.extend_from_slice(data);
            Ok(data.len())
        })
        .unwrap();
    transfer.perform().unwrap();
    drop(transfer);

    println!("{:?}", dst);
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.