0

I want to create a new Context object and then return it if it works. However, Rust says that &context does not live long enough.

How can I force context to live as long as Bo in this case? Is it not enough to use the lifetime parameter b in the definition of the return type?

impl<'b> Bo {
    pub fn new() -> Result<&'b Context, BoError> {
        match Context::new() {
            Ok(context) => {
                return Ok(&context);
            }
            Err(e) => Err(BoError {}),
        }
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Johannes Mittendorfer
  • 1,102
  • 10
  • 17
  • *and then return it if it works* — you aren't returning the `Context`, you are trying to return a *reference to it*. Once the function exits, the `Context` is destroyed and any references to it are invalidated. You just attempted to add memory unsafety to your program and Rust prevented it. Return `Result` instead. – Shepmaster Jul 19 '17 at 12:33
  • I know. But what is the way to make `context` live as long as `Bo`? – Johannes Mittendorfer Jul 19 '17 at 12:36
  • 1
    You cannot *make* anything live longer via lifetimes; [they are descriptive, not prescriptive](https://doc.rust-lang.org/stable/book/first-edition/lifetimes.html#lifetimes-1). Return `Result` instead. There's nothing inside `Context` that cares about `Bo`, so there's no reason that the `Context` should not outlive `Bo`. If `Context` had a reference to `Bo`, then the compiler would prevent it from outliving it. – Shepmaster Jul 19 '17 at 12:46

0 Answers0