Returning reference to local/temporary variable

New to Rust. Consider the below code.

fn c1() -> &'static dyn Fn() -> () {
    let x = || ();
    &x // error[E0515]: cannot return reference to local variable `x`
}

fn c2() -> &'static dyn Fn() -> () {
    &|| () // okay
}

I understand the error[E0515] in c1. But in c2, isn't the closure assigned to a temporary local variable behind the scenes? Why no error[E0515] in c2?

Due to the constant promotion.

To make c1 work, use promotion in let var: &'static which is equivalent to the &'static in return position. See 1414-rvalue_static_promotion - The Rust RFC Book

fn c1() -> &'static dyn Fn() -> () {
    let x: &'static _ = &|| ();
    x
}

If you're curious about the details, like what's the requirements for a promotion, refer to 3027-infallible-promotion - The Rust RFC Book and GitHub - rust-lang/const-eval: home for proposals in and around compile-time function evaluation

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.