Daniel
Daniel

Reputation: 21

rust - variable doesn't live long enough

Anyone knows why the compiler complains?

fn main() {
    struct Z<'a, 'b> {
        a: &'a i32,
        b: &'b i32,
    }

    let z: Z;
    {
        let a = 1;
        {
            let b = 2;
            z = Z { a: &a, b: &b };
            println!("{}", z.b);
        }
        println!("{}", z.a);
    }
}
error[E0597]: `b` does not live long enough
  --> src/main.rs:12:31
   |
12 |             z = Z { a: &a, b: &b };
   |                               ^^ borrowed value does not live long enough
13 |             println!("{}", z.b);
14 |         }
   |         - `b` dropped here while still borrowed
15 |         println!("{}", z.a);
   |                        --- borrow later used here

I am only using the z.a in the println, is this some compiler limitations?

Upvotes: 0

Views: 527

Answers (1)

user8866053
user8866053

Reputation:

The compiler is telling you that b does not live long enough because b does, in fact, not live long enough. It's dropped (deallocated) when its scope ends, which is 'at' the inner curly brace. However, Z is still holding a reference to b when that happens, which means Z is invalid. So, for Z to exist, b must live longer.

It doesn't matter that only z.a is used, z.b is still part of z, and the structure as a whole doesn't make sense without it. So you could say it's a compiler limitation that this code won't compile, as it's technically okay, but structurally, it's not okay. A reference is being held to a value which does not exist, so the code does not compile.

Upvotes: 3

Related Questions