'cannot borrow `vec` as mutable because it is also borrowed as immutable

I am new on Rust and I can not fix this error. Need help with this issue. The issue occurs when i try to delete the last item on the vec. Then i get this error 'cannot borrow vec as mutable because it is also borrowed as immutable'. What I am doing wrong?

fn valid_braces(s: &str) -> bool {
    let s1 = s.chars();
    let mut vec = Vec::new();
    for x in s1 {
        let i = x.to_string();
        if i == "{" || i == "[" || i == "(" {
            vec.push(i);
        } else {
            if vec.len() == 0 {
                return false;
            }
            let curr = vec.last().unwrap();

            vec.remove(vec.len() - 1); // this line is source of the problem
            if curr == "{" {
                if i != "}" {
                    return false;
                }
            }
            if curr == "(" {
                if i != ")" {
                    return false;
                }
            }
            if curr == "[" {
                if i != "]" {
                    return false;
                }
            }
        }
    }
    if vec.len() == 0 {
        return false;
    } else {
        return true;
    };
}
error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable
  --> src/lib.rs:14:13
   |
12 |             let curr = vec.last().unwrap();
   |                        ---------- immutable borrow occurs here
13 | 
14 |             vec.remove(vec.len() - 1); // this line is source of  the problem
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
15 |             if curr == "{" {
   |                ---- immutable borrow later used here

Playground.



Solution 1:[1]

You try to remove the last element while holding a reference to it. If Rust would allow you to do that, you would hold a dangling reference! (Rust would disallow it even if you'd remove an unrelated element, and even if it would not affect the reference at all because the removed element is after that and it won't be moved, because Rust can't tell when it's valid and when not, so this is a rule of thumb: you cannot hold mutable and immutable references at the same time).

Instead you should at the same time remove the element and return it, and this is exactly what Vec::pop() method does:

let curr = vec.pop().unwrap();
if curr == "{" { /* ... */ }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chayim Friedman