Rust quiz— lifetime 1 Link to heading
I have a quiz to test your understanding of Rust lifetime parameters and their implications. This simple exercise really helped me understand the lifetime behavior in Rust. Without running the compiler, can you tell which of the test cases will succeed/fail?
#[derive(Debug)]
struct MyRef<'a, T> {
s: &'a T
}
impl<'a, T> MyRef<'a, T> {
fn test1(&self) -> Self {
Self { s: self.s }
}
fn test2(&self) -> MyRef<T> {
Self { s: self.s }
}
fn test3(&self) -> MyRef<'a, T> {
Self { s: self.s }
}
fn test4(&self) -> MyRef<'_, T> {
Self { s: self.s }
}
fn test5<'b>(&'b self) -> MyRef<'_, T> {
Self { s: self.s }
}
fn test6<'b>(&'b self) -> MyRef<'a, T> {
Self { s: self.s }
}
fn test7<'b>(&'b self) -> MyRef<'b, T> {
Self { s: self.s }
}
}
fn main() {
let s = String::from("this is string");
let t1;
let t2;
let t3;
let t4;
let t5;
let t6;
let t7;
{
let sr = MyRef { s: &s };
t1 = sr.test1();
t2 = sr.test2();
t3 = sr.test3();
t4 = sr.test4();
t5 = sr.test5();
t6 = sr.test6();
t7 = sr.test7();
}
dbg!(t1);
dbg!(t2);
dbg!(t3);
dbg!(t4);
dbg!(t5);
dbg!(t6);
dbg!(t7);
}
For each failure cases, if any, can you explain why it fails to compile?