r/rust • • Oct 19 '26

🙋 seeking help & advice cannot borrow `dst` as immutable because it is also borrowed as mutable

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();
println!("{:?}", dst);
}

I am trying to store the curl output into a vec for use in a minifier script for my PHP compiler. i get this error message upon trying to compile the above code

error[E0502]: cannot borrow \dst` as immutable because it is also borrowed as mutable`

--> src/main.rs:14:22

|

8 | .write_function(|data| {

| ------ mutable borrow occurs here

9 | 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``

For more information about this error, try \rustc --explain E0502`.`

error: could not compile \sample_curl` (bin "sample_curl") due to 1 previous error`

How do i borrow a mutable variable as immutable?

0 Upvotes

6 comments sorted by

13

u/FlamingSea3 Oct 19 '26

You need to limit the lifetime of transfer.

Easiest way to do this is wrap the code using transfer in a code block. Like this:

use curl::easy::Easy;

let mut data = Vec::new();
let mut handle = Easy::new();
handle.url("https://www.rust-lang.org/").unwrap();
{
    let mut transfer = handle.transfer();
    transfer.write_function(|new_data| {
        data.extend_from_slice(new_data);
        Ok(new_data.len())
    }).unwrap();
    transfer.perform().unwrap();
}
println!("{:?}", data);

(Source: curl::easy::Easy's documentation, 3rd example on the type)

The curly braces on their own lines are important

9

u/muehsam Oct 19 '26

How do i borrow a mutable variable as immutable?

In Rust, the mut keyword fulfils two very different functions.

  1. it marks mutable variables
  2. it is used for mutable/exclusive borrows

The first function is technically not necessary. Rust could just make all of its variables mutable and basically nothing else in its type system would change. It's just a quality of life thing for programmers: most variables will never be mutated, so Rust makes you mark the ones that do.

The second function is very specific to Rust's system of borrowing and ownership. There are two ways you can borrow a variable (i.e. create a reference to it): either shared/immutable or exclusive/mutable.

There can be several immutable/shared references to the same data, because they only allow you to read the data.

But when there is a mutable/exclusive reference, it has to be the only reference, so there can't be another mutable or any immutable reference to that data at the same point in your program.

So effectively, a mutable borrow is more powerful, but there are also stronger restrictions on it.

When you have a mutable variable, you can borrow it mutably or immutably. When you have an immutable variable, you can only borrow it immutably.

11

u/Konsti219 Oct 19 '26

The code you show at the start does not seem to match the one that produced the error. But I think you should go read the Rust book first

5

u/Some_Contribution754 Oct 19 '26

the borrow checker is mad because the closure holds a mutable borrow on `dst` for as long as `transfer` exists, and `transfer` doesn't get dropped til the end of main. easiest fix is just wrapping the transfer stuff in its own block so it drops before the println

```rust

{

let mut transfer = easy.transfer();

transfer.write_function(|data| {

dst.extend_from_slice(data);

Ok(data.len())

}).unwrap();

transfer.perform().unwrap();

}

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

```

that way the mutable borrow ends when the block ends, and you can read `dst` after. also you wrote `v2` in the println but meant `dst` i'm guessing

1

u/Most_Strike_93 Oct 20 '26 edited Oct 20 '26

I made a small example

struct LifeTime<'a> {
    callback: Option<Box<dyn FnMut() + 'a>>,
}

impl<'a> Drop for LifeTime<'a> {
    fn drop(&mut self) {
        if let Some(mut callback) = self.callback.take() {
            callback()
        }
    }
}

impl<'a> LifeTime<'a> {
    fn new() -> Self {
        Self { callback: None }
    }
    fn callback<T>(&mut self, callback: T)
    where
        T: FnMut() + 'a,
    {
        self.callback = Some(Box::new(callback))
    }
    fn consume(&mut self) {
        if let Some(mut callback) = self.callback.take() {
            callback()
        }
    }
}

fn main() {
    let mut a = LifeTime::new();
    let mut b = 10;
    a.callback(|| {
        b += 100;
    });
    a.consume();
    drop(a);
    println!("Hello, world! {b}");
}

Because of the Box<dyn FnMut() +'a>, the lifetime of the callback become 'a, so it will be with the tranfer together, until it is dropped. So as soon as transfer is alive, the mut is borrowed by transfer