Skip to content

Confusing message when using unsafe to initialize statics #94077

Description

@mejrs

Given the following code:

fn foo() {
    unsafe {
        static BAR: u32 = std::mem::transmute(0_i32);
    }
}

The current output is:

Compiling playground v0.0.1 (/playground)
warning: unnecessary `unsafe` block
 [--> src/lib.rs:2:5
](https://play.rust-lang.org/#)  |
2 |     unsafe {
  |     ^^^^^^ unnecessary `unsafe` block
  |
  = note: `#[warn(unused_unsafe)]` on by default

error[[E0133]](https://doc.rust-lang.org/stable/error-index.html#E0133): call to unsafe function is unsafe and requires unsafe function or block
 [--> src/lib.rs:3:27
](https://play.rust-lang.org/#)  |
3 |         static BAR: u32 = std::mem::transmute(0_i32);
  |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior

For more information about this error, try `rustc --explain E0133`.
warning: `playground` (lib) generated 1 warning
error: could not compile `playground` due to previous error; 1 warning emitted

Ideally the output should look like:

It could suggest moving the unsafe block:

static BAR: u32 = unsafe { std::mem::transmute(0_i32) };
                  ^^^^^^

Or perhaps this should be valid? It is inside an unsafe block after all.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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