#Concept of Lifetime

32 messages · Page 1 of 1 (latest)

turbid osprey
#

What's the purpose of Lifetime I just need a example rather than this

let a = String::from("value");
let result;
{
  let b = String::from ("Value 123");
  result = get_max_val(&a,&b);
}
println!("{},&result);

fn get_max_val<'a>(a:&'a str,b:&'a str) -> &'a str{
 ..... Giving the max len string
}
long hazel
turbid osprey
inland light
#

you are saying that the lifetime return type of the function is the same as both of the inputs

turbid osprey
#

So what if they both have diffrence life time aka <'a,'b>

inland light
inland light
turbid osprey
#

B

#

Inside the scope one....

long hazel
#
fn main() {
    let s = "hello".to_string();
    let ref_to_s = &s;
    drop(s);
    println!("{}", *ref_to_s); // ERROR
}

In this example you can't use ref_to_s because it isn't valid anymore. The lifetime of s has expired

#

in this example the compiler was able to figure out all the lifetimes itself

inland light
#

then the return type lifetime is the same as 'b

long hazel
#

but sometimes you need to specify it manually

inland light
#

you mean this? fn get_max_val<'a>(a: &'a str, b: &'b str) -> &'b str

long hazel
#

(note: in C there would be no error and it would probably just segfault or something)

turbid osprey
turbid osprey
inland light
#

or just dont drop it

long hazel
turbid osprey
inland light
inland light
turbid osprey
turbid osprey
long hazel
long hazel
#

@turbid osprey here's an example in C that shows how you need to handle lifetimes manually

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    char* s = malloc(12); 
    strcpy(s, "hello there");
    // s is a reference to a string that lives in the heap

    printf("%s\n", s); // this is ok
    free(s); // equivalent to `drop` in Rust
    printf("%s\n", s); // UB

    return 0;
}
#

this is an obvious example but if you're returning s from a function it might be tough to keep track of whether or not it has been freed