Cannot borrow `z` as mutable more than once at a time

fn main(){
    let mut z = 4;
    my(&mut z);
    my(&mut z);

fn my(_x:&'static i32 ){



   Compiling playground v0.0.1 (/playground)
error[E0597]: `I do not live long enough
 --> src/
3 |     my(&mut z);
  |     ---^^^^^^-
  |     |  |
  |     |  borrowed value does not live long enough
  |     argument requires that `z` is borrowed for `'static`
7 | }
  | - `I'm dropped here while still borrowed

error[E0499]: cannot borrow `I'm as mutable more than once at a time
 --> src/
3 |     my(&mut z);
  |     ----------
  |     |  |
  |     |  first mutable borrow occurs here
  |     argument requires that `z` is borrowed for `'static`
4 |     my(&mut z);
  |        ^^^^^^ second mutable borrow occurs here

Some errors have detailed explanations: E0499, E0597.
For more information about an error, try `rustic --explain E0499`.
error: could not compile `playground` due to 2 previous errors

  1. I understand the first error. Z is not live long enough
  2. But why the second error happens. It already dropped after the first function call right?
  3. what is the meaning of 'static lifetime

You made the same error twice.

'static means the lifetime is the entire time until the program finishes, and z doesn't live that long, so it's an error.

That's ok but.

Assume its lives entire program and why it cannot borrow `z as mutable more than once at a time?

But after first call over its dropped right?

It isn't, because the function requires it to stay for 'static.

The analysis is not interprocedural, so the caller has to work with full 'static requirements, even if the current function implementation doesn't exploit that. That could change within, not affecting the function signature -- it would be totally valid for that function to save the reference in a static variable.

Ok so what is static borrow meas

As noted above:

An example is a literal string like:

let message = "hello";

Here the bytes of the "hello" string are just hardwired into the executable code of your program. They are there for the entire life of the program. They are 'static. The message variable becomes a reference to those bytes &str.

You can get your code to compile by making "z" a reference to a static value.

       let mut z: &'static u32 = &4u32;

Or let the compiler infer the type of z:

        let mut z = &4u32;

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.