• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by John Dev


29 Nov, 2024

Updated at 12 Dec, 2024

Rust lifetime problem

I'm learning about lifetime knowledge. I haven't made any progress for a long time.

I think it's very difficult. The difficulty is that official documents and online blogs only explain a specific case.

For example, return the longer of two strings, or explain a little about lifetime in struct.

I can't find a document that explains the specific steps of the compiler.

Of course, I'm not asking for very specific details, after all I'm not looking at compiler implementations.

However, at least there is a relatively strict document that covers all these cases as much as possible.

Many documents found on the Internet explain lifetime in a way that the author thinks he understands.

I am very confused. Programming should be strict and should not be based on self-knowledge.

I think the fundamental reason why lifetime is difficult to master is that the official documentation does not explain in detail how lifetime annotation guides the compiler to perform borrow checks.

For example the following code:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

Basically everyone first gets to know lifetime from this example.

But, let me be honest. I still can't understand how the syntax in this example relates to the behavior of the compiler. I don't think it's very simple.

In this case, I have many ways to self-hypnotize myself: I already understand.

For example, I could describe this syntax like this.

Dear rust compiler, when calling this function, please check for me :

  • The reference returned cannot exceed the lifetime of the original object referenced by the first parameter
  • The reference returned cannot exceed the lifetime of the original object referenced by the second parameter

Maybe in this case, I'm right to think this way.

But in the following example, I can't think like this.

fn biggest<'a, 'b>(x: &'a i32, y: &'b i32) -> &'a i32 {
    if *x > *y {
        x
    } else {
        y
    }
}

In this case, the compiler reports an error: error: lifetime may not live long enough

I don't have the syntax and knowledge demonstrated in the first example to know what mistake I made in the second example.

Yes, this is the biggest problem in rust lifetime learning. I cannot face new cases through the existing examples I have learned.

So, first of all, I still want someone to explain in more general terms what information the lifetime annotation tells the compiler. Try to use a stricter, more general statement.

Okay, regarding the second example, why does it not compile, can anyone answer it, thank you very much, I have been stuck here for a long time.

1 post - 1 participant

Read full topic