1

I'm trying to understand how borrowing works in rust. So after read some topics of the rust book. I got stuck, trying to understand why this code doesn't compile.

Code
fn main() {
    let mut a = String::from("yes");
    let b = function(&a);
    a.clear();
    println!("Hello {}", b);
}

fn function(a :&String) -> &str{
    if a == "yes" {
        "OK"
    }
    else{
        "NO"
    }
}
The compiler gives this error:
   Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let b = function(&a);
  |                      -- immutable borrow occurs here
4 |     a.clear();
  |     ^^^^^^^^^ mutable borrow occurs here
5 |     println!("Hello {}", b);
  |                          - immutable borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

But I don't understand why the scope of &a doesn't ends with the function scope.

  • and https://stackoverflow.com/questions/40325690/what-is-lifetime-elision-in-very-simple-terms and https://stackoverflow.com/questions/31609137/why-are-explicit-lifetimes-needed-in-rust – Stargateur Jul 17 '19 at 16:36

1 Answers1

1

You don't precise the lifetime of the output of your function function. So it's assumed by the borrow checker to be the same as the argument (see lifetime elision rules).

You have to tell the borrow checker that those lifetimes aren't the same (meaning in this case that the output slice isn't dependent of the input one). More precisely in your case it's static.

Change your function declaration to

fn function(a :&String) -> &'static str{
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758