#Concept of Lifetime
32 messages · Page 1 of 1 (latest)
well the basic purpose is that you're telling the compiler how long the reference is valid for
Means a type of reminder .??
you are saying that the lifetime return type of the function is the same as both of the inputs
Ok
So what if they both have diffrence life time aka <'a,'b>
this doesnt work because b is dropped before the print
which one are you returning
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
then the return type lifetime is the same as 'b
but sometimes you need to specify it manually
Ohhh
you mean this? fn get_max_val<'a>(a: &'a str, b: &'b str) -> &'b str
(note: in C there would be no error and it would probably just segfault or something)
Any way to fix it.??
I am from java background 🙂
use the ref before you drop it
or just dont drop it
well my code is nonsensical, it drops the string and then tries to print it
Dayem it's brutal making my mind coocked
also you cant drop s because it is borrowed
drop is just fn drop<T>(_x: T) {}
Yeah I see
Got it I just looked the docs
so in this example you're telling the compiler: "we return a reference to a string, and this reference is valid only when a and b are valid references"
Hmmm
Got it
@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