bilosikia
bilosikia

Reputation: 71

rust lifetime problem, why the first call not compile error?

#[derive(Debug)]
struct NumRef<'a>(&'a i32);

impl<'a> NumRef<'a> {
    // my struct is generic over 'a so that means I need to annotate
    // my self parameters with 'a too, right? (answer: no, not right)
    fn some_method(&'a mut self) {}
}

fn main() {
    let mut num_ref = NumRef(&5);
    num_ref.some_method(); // mutably borrows num_ref for the rest of its lifetime
    num_ref.some_method(); // compile error
    println!("{:?}", num_ref); // also compile error
}

'a is should be 'static, num_ref's lifetime is shorter then 'static

Upvotes: 2

Views: 78

Answers (1)

Masklinn
Masklinn

Reputation: 42592

The problem is that you've told Rust that some_method needs self for 'a.

But by definition 'a lives for longer than the instance of NumRef.

This means the only way to fulfill your requirement is to create a borrow which lasts for the entire lifetime of the instance, aka as soon as the method is called you're completely locked out.

You can just remove the lifetime bound from the self entirely:

impl<'a> NumRef<'a> {
    fn some_method(&mut self) {}
}

These lifetimes are essentially unrelated: here some_method cares about NumRef, not 'a.

Upvotes: 3

Related Questions