Question rust returning a reference to a integer from a function was tagged as duplicate, and almost is.
The question Why can I return a reference to a local literal but not a variable? was referenced, suggesting that &42 were static.
However, code (playground)
use std::ops::Deref;
struct Curse<T>(T);
impl<T> Deref for Curse<T> {
type Target = usize;
fn deref(&self) -> &<Self as Deref>::Target {
&42 // wat
}
}
fn main() {
let a = 123;
let c = *{
let b = Curse(a);
b.deref()
};
println!("{a} {c}");
}
will result in:
Exited with status 101
Standard Error
Compiling playground v0.0.1 (/playground)
error[E0597]: `b` does not live long enough
--> src/main.rs:18:9
|
17 | let b = Curse(a);
| - binding `b` declared here
18 | b.deref()
| ^ borrowed value does not live long enough
19 | };
| - `b` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Standard Output
So, in this case, the lifetime seems conditionned by the lifetime of &self