Skip to content

Bad diagnostics when constructing tuple variant with static ref inside const #101363

@juntyr

Description

@juntyr

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=faa286146f7760bc7c1be85eaac73f9d

const OPTIONAL_SLICE_V1: Option<&'static [u8]> = Some(&{
    let array = [1, 2, 3];
    array
});

The current output is (both on stable, beta, and nightly):

error[[E0716]](https://doc.rust-lang.org/stable/error-index.html#E0716): temporary value dropped while borrowed
 --> src/lib.rs:1:56
  |
1 |    const OPTIONAL_SLICE_V1: Option<&'static [u8]> = Some(&{
  |   __________________________________________________-_____^
  |  |__________________________________________________|
  | ||
2 | ||     let array = [1, 2, 3];
3 | ||     array
4 | || });
  | || ^-
  | || ||
  | ||_|temporary value is freed at the end of this statement
  |  |_|using this value as a constant requires that borrow lasts for `'static`
  |    creates a temporary which is freed while still in use

For more information about this error, try `rustc --explain E0716`.

It is, however, possible to get this code to compile by using the struct initialiser syntax for the tuple variant:

const OPTIONAL_SLICE_V2: Option<&'static [u8]> = Some {
    0: &{
        let array = [1, 2, 3];
        array
    },
};

Given that this initialiser isn't used very often, it took me a while to remember it as an alternative and to figure out that the use of Some as a function was causing the error.

Ideally, the error message should also suggest something like

help: try using a struct initializer instead: `Some { 0: ... }`

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions