Skip to content

It should be possible to get a mutable reference to a ZST literal #103821

Open
@joshlf

Description

@joshlf

The following code is legal:

fn get_mut_ref<'a>() -> &'a mut [u8] {
    &mut []
}

However, if we instead use (), it's no longer legal:

fn get_mut_ref<'a>() -> &'a mut () {
    &mut ()
}

We get this error:

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

Is there a reason that the former is legal while the latter is not? I would expect the latter to be legal - in the general case, it'd be great if it were legal for any ZST, although I'm sure that's more complicated (especially in a generic context).

On Fuchsia, we're currently using this hack to work around this limitation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-zstArea: Zero-sized types (ZSTs).T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions