I have rust code like something below, want to implement something that one liner instead of commented code. In my code. Push or Pop mutable stack is fine as commented code is working perfectly. How can I design the code structure to tell compiler it is ok. Is that only option for me is Rc<RefCell<Vec<_>>> ?
impl Solution {
pub fn min_add_to_make_valid(s: String) -> i32 {
s.chars().fold(vec!(), |mut stack, item| {
if item == '(' {
stack.push(item);
} else {
stack.last().map_or_else(|| {stack.push(item);}, |&val| if val == '(' {stack.pop();} )
// if stack.last().is_some() && *stack.last().unwrap() == '(' {
// stack.pop();
// } else {
// stack.push(item);
// }
}
stack
}).len() as i32
}
}
Line 7, Char 42: cannot borrow `stack` as mutable because it is also borrowed as immutable (solution.rs)
|
7 | stack.last().map_or_else(|| {stack.push(item);}, |&val| if val == '(' {stack.pop();} )
| ----- ----------- ^^ ----- second borrow occurs due to use of `stack` in closure
| | | |
| | | mutable borrow occurs here
| | immutable borrow later used by call
| immutable borrow occurs here
Line 7, Char 66: cannot borrow `stack` as mutable because it is also borrowed as immutable (solution.rs)
|
7 | stack.last().map_or_else(|| {stack.push(item);}, |&val| if val == '(' {stack.pop();} )
| ----- ----------- ^^^^^^ ----- second borrow occurs due to use of `stack` in closure
| | | |
| | | mutable borrow occurs here
| | immutable borrow later used by call
| immutable borrow occurs here
error: aborting due to 2 previous errors