Skip to content

Suggestion to replace std::mem::uninitialized with MaybeUninit is not actionable #65432

Closed
@gnzlbg

Description

@gnzlbg

When Foo below is defined in a crate outside your control, code that currently does this:

struct Foo(&'static i32);
fn main() {
    let _x: Foo = unsafe { std::mem::uninitialized() };
}

(Playground)

gets a warning suggesting to use MaybeUninit instead

   Compiling playground v0.0.1 (/playground)
warning: the type `Foo` does not permit being left uninitialized
 --> src/main.rs:4:28
  |
4 |     let _x: Foo = unsafe { std::mem::uninitialized() };
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^^
  |                            |
  |                            this code causes undefined behavior when executed
  |                            help: use `MaybeUninit<T>` instead
  |
  = note: `#[warn(invalid_value)]` on by default
note: References must be non-null (in this struct field)
 --> src/main.rs:1:12
  |
1 | struct Foo(&'static i32);
  |            ^^^^^^^^^^^^

    Finished dev [unoptimized + debuginfo] target(s) in 0.76s
     Running `target/debug/playground`

This warning is currently not actionable, since Foo cannot be modified, and MaybeUninit<T> does not support T: !Copy.

Instead, the suggestion "help: use MaybeUninit<T> instead" should only be shown if T: Copy.

A different suggestion could be shown, suggesting to change the type definition instead, and maybe reminding the user that their code exhibits undefined behavior, even though there is nothing that the user might be able to do about this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintsArea: Lints (warnings about flaws in source code) such as unused_mut.C-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler 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