Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Temporary Lifetime Extension in different cases
I'm reading https://blog.m-ou.se/super-let/#temporary-lifetime-extension
While this is super helpful for me to understand what and why Temporary Lifetime Extension(TLE) is, I still have questions about some cases:
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn new(x: i32, y: i32) -> Self {
Point {x, y}
}
}
#[derive(Debug)]
struct BigPoint<'a> {
p: &'a Point,
}
impl<'a> BigPoint<'a> {
fn new(p: &'a Point) -> Self {
Self {
p,
}
}
fn something (self) {}
}
{
// case 1
let bp1 = BigPoint::new(&Point{x: 1, y: 2});
bp1.something();
}
{
// case 2
let bp2 = BigPoint { p: &Point::new(1, 2)};
bp2.something();
}
{
// case 3
let bp3 = BigPoint::new(&Point::new(2, 2));
bp3.something();
}
Case 3 does not compile. The error: "temporary value is freed at the end of the statement".
But comparing case 1/2/3
let bp1 = BigPoint::new(&Point{x: 1, y: 2});
let bp2 = BigPoint { p: &Point::new(1, 2)};
let bp3 = BigPoint::new(&Point::new(2, 2));
why case 1 works while case 3 doesn't?
why case 2 works while case 3 doesn't?
I failed to understand the pattern -- more specifically how the following rules apply/not apply to cases above
#t-lang > Understanding lifetime extension docs @
#t-lang/temporary-lifetimes-2024 > 2024-03-07 @
1 post - 1 participant
🏷️ rust_feed