Search code examples
rustimmutabilitymutable

cloning a mut reference in order to use the mut reference elsewhere


I had an error using function because borrowing a mutable, if there is also an immutable borrow, is not allowed just like borrowing a mutable multiple times.

pub fn _function(list: &mut Vec<char>) {
     for (n, c) in list.iter().enumerate() {
         if *c == ' ' {
             list.remove(n);
         }
     }
}
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
 --> src/lib.rs:4:14
  |
2 |      for (n, c) in list.iter().enumerate() {
  |                    -----------------------
  |                    |
  |                    immutable borrow occurs here
  |                    immutable borrow later used here
3 |          if *c == ' ' {
4 |              list.remove(n);
  |              ^^^^^^^^^^^^^^ mutable borrow occurs here

The only solution I came across is cloning the list.

pub fn _function(list: &mut Vec<char>) {
     for (n, c) in list.clone().iter().enumerate() {
         if *c == ' ' {
             list.remove(n);
         }
     }
}

I was wondering if there is any other solution for using these two functions without cloning the list and using more memory.


Solution

  • There's not really a general way to read and modify a vec at the same time. But there are ad-hoc solutions for specific cases.

    Here, you can use retain which modifies the vec in place to keep only the elements verifying a predicate:

    pub fn _function(list: &mut Vec<char>) {
         list.retain(|&c| c != ' ');
    }