3

Why does the following code not compile?

fn main() {
    let mut s = "test".to_string();

    if let Some(first_five) = s.get(..5) {
        // ...
    }
    else {
        s.push('s');
    }
}

The error I get says immutable borrow occurs on line 4 (s.get(..5)) and that the immutable borrow ends on line 9. Why does it end on line 9? It seems that the scope for s.get(..5) should have ended on line 6, which would release the immutable reference, allowing the mutable reference to be taken on line 8 (s.push('s')).

The following code is a work around but it is not very idiomatic and not something I would like to use.

fn main() {
    let mut s = "test".to_string();

    let mut flag = false;
    if let Some(first_five) = s.get(..5) {
        //  ...
    }
    else {
        flag = true;
    }

    if flag {
        s.push('s');
    }
}

To reiterate, is there a reason that s is borrowed for much longer than it needs to be? The return value of s.get(..5) is out of scope and inaccessible from the else clause so why is the string still being borrowed in the else clause?

nickeb96
  • 789
  • 1
  • 10
  • 16
  • If you are not going to use `first_five` (silly assumption, probably) you can avoid the borrow with `Some(_)`, `.is_some()`, or just checking the length of the string. – MB-F May 02 '18 at 07:00

0 Answers0