Skip to content

Misleading error message about "call to unsafe function" #44674

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

Closed
ruuda opened this issue Sep 18, 2017 · 2 comments
Closed

Misleading error message about "call to unsafe function" #44674

ruuda opened this issue Sep 18, 2017 · 2 comments

Comments

@ruuda
Copy link
Contributor

ruuda commented Sep 18, 2017

The following code generates a misleading error message on Rust 1.20.0:

fn main() {
    use std::mem;
    unsafe {
        const MAGIC: i32 = mem::transmute([1u8, 2, 3, 4]);
        println!("{}", MAGIC);
    }
}

Observed output:

error[E0133]: call to unsafe function requires unsafe function or block
 --> src/main.rs:4:28
  |
4 |         const MAGIC: i32 = mem::transmute([1u8, 2, 3, 4]);
  |                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function

It is misleading, because the call is in fact inside an unsafe block. Expected output:

error[E0015]: calls in constants are limited to struct and enum constructors

On the current nightly the problem is even worse because the compiler also warns about an unused unsafe block, while at the same time telling that an unsafe block is required.

@arielb1
Copy link
Contributor

arielb1 commented Sep 18, 2017

The error is correct - every item is a scope of its own. You'll have to put an unsafe block around the function:

fn main() {
    use std::mem;
    
        const MAGIC: i32 = unsafe {
            mem::transmute([1u8, 2, 3, 4])
        };
        println!("{}", MAGIC);
}

@Mark-Simulacrum
Copy link
Member

This is a duplicate of #35716. Closing.

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

3 participants