How do I compile Rust 0.10 with multiple closures sharing a captured variable?

StackOverflow https://stackoverflow.com/questions/22852174

  •  27-06-2023
  •  | 
  •  

سؤال

Since upgrading to Rust 0.10 today I've found this code no longer works:

let mut outer_value = 0;

let add = |x| {
    outer_value += x;
};

let multiply = |x| {
    outer_value *= x;
};

//Showing commented code to demonstrate intent
//add(4);
//multiply(6);
//println!("{:d}", outer_value);

This gives me these compiler errors:

closures.rs:13:20: 15:6 error: cannot borrow `outer_value` as mutable more than once at a time
closures.rs:13     let multiply = |x| {
closures.rs:14         outer_value *= x;
closures.rs:15     };
closures.rs:14:9: 14:20 note: borrow occurs due to use of `outer_value` in closure
closures.rs:14         outer_value *= x;
                       ^~~~~~~~~~~
closures.rs:9:15: 11:6 note: previous borrow of `outer_value` occurs here due to use in closure; the mutable borrow prevents subsequent moves, borrows, or modification of `outer_value` until the borrow ends
closures.rs:9     let add = |x| {
closures.rs:10         outer_value += x;
closures.rs:11     };
closures.rs:22:2: 22:2 note: previous borrow ends here
closures.rs:6 fn main() {
...
closures.rs:22 }
               ^
error: aborting due to previous error

This worked in Rust 0.9. Is there still a way to make this work in some fashion?

Note: I think the Nightly build and 0.10 build are one and the same today (3rd April), but I've tested with both. Same result.

هل كانت مفيدة؟

المحلول

That worked in Rust 0.9? I guess that's one of the unsoundness bugs that was patched this cycle.

That code does indeed require multiple mutable borrows and so the 0.9 behaviour was not correct; the 0.10 behaviour is correct.

There are two things you can do:

  • refactor your code so that this requirement is not necessary, or
  • use RefCell<T> instead of T, to use runtime borrow checking.
  • use Cell<T> instead of T, maintaining a local copy of the object rather than doing borrowing.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top