Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

functions that return direct static references to const fns fail to compile #76180

Closed
Cobrand opened this issue Aug 31, 2020 · 1 comment
Closed

Comments

@Cobrand
Copy link
Contributor

Cobrand commented Aug 31, 2020

When having a function that returns a static reference, you can return borrows to direct structs such as A(5) but not const fns which return the same struct such as A::new(5). It's kind of tricky to explain, the example is easier to understand.

Example

#[derive(Copy, Clone)]
pub struct A(i32);

impl A {
    pub const fn new(i: i32) -> A {
        A(i)
    }
}

// comment to make it compile
fn not_good() -> &'static A {
    &A::new(5) // <- this should work since A::new is const fn
}

fn good1() -> &'static A {
    &A(5)
}

fn good2() -> &'static A {
    static THIS_DOES_WORK: &'static A = &A::new(5);
    THIS_DOES_WORK
}

fn main() {}

playground

Current Behavior (1.46.0 Stable)

error[E0515]: cannot return reference to temporary value
  --> src/main.rs:13:5
   |
13 |     &A::new(5)
   |     ^---------
   |     ||
   |     |temporary value created here
   |     returns a reference to data owned by the current function

There is a borrow error when there shouldn't be: this error is perfectly valid when A::new is not const fn, but if A::new is const fn, it shouldn't output an error.

@jonas-schievink
Copy link
Contributor

const fn calls are deliberately not promoted to statics. Please refer to rust-lang/const-eval#19 for details on why that is. Closing as expected behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants