0

Rust newbie here. Can anyone please help me understand why Rust doesn't like this code and how it can be fixed?

struct Foo {
    num: u32
}

struct Bar<'a> {
    foo: Foo,
    num_ref: &'a u32,
}

fn foo<'a>() -> Bar<'a> {
    let f = Foo { num: 2 };
    let n: &'a u32 = &f.num;
    return Bar { foo: f, num_ref: n };
}

fn main() { }

I basically want a function that returns a Bar, which owns Foo and a reference to num (owned by Foo).

Link to playground

Error:

error[E0597]: `f.num` does not live long enough
  --> src/main.rs:12:23
   |
12 |     let n: &'a u32 = &f.num;
   |                       ^^^^^ borrowed value does not live long enough
13 |     return Bar { foo: f, num_ref: n };
14 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 10:8...
  --> src/main.rs:10:8
   |
10 | fn foo<'a>() -> Bar<'a> {
   |        ^^

Thanks in advance!

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Felipe Lima
  • 10,530
  • 4
  • 41
  • 39
  • 1
    I really do ask myself why you ever want that? You already own the variable, why do you need a reference to it? You can get it for free, you don't have to waste 8bytes for that. – hellow Jan 08 '19 at 07:37

1 Answers1

2

The compiler is saying that you are borrowing f.num inside the scope of the function and once this scope is done the reference to f.num doesn't live anymore.

I'm not sure if this example of code can help you, let me know. I don't know if "a reference to num" in your case is important but it doesn't seem to be necessary and maybe you didn't see how to achieve that.

I recommend you to read and take the time to understand how the ownership system works in Rust. It can be a little bit tedious at the beginning but you will master the concept with practice.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140