Const and unsafe blocks

Why does this not work?

const _:() = unsafe {
    const VAL: usize = std::mem::transmute(5_isize);
};

Here's the error:

warning: unnecessary `unsafe` block
 --> src/lib.rs:1:14
  |
1 | const _:() = unsafe {
  |              ^^^^^^ unnecessary `unsafe` block
  |
  = note: `#[warn(unused_unsafe)]` on by default

error[E0133]: call to unsafe function is unsafe and requires unsafe function or block
 --> src/lib.rs:2:24
  |
2 |     const VAL: usize = std::mem::transmute(5_isize);
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior

error: aborting due to previous error; 1 warning emitted

Playground link.

This is because the scope of the unsafe block does not extend to the definition of the constant, even if the constant is defined in the unsafe block.

1 Like

Is there a reason for that?

The body of the definition of the constant is a different function in some sense.

1 Like

Ah I see. It's frustrating in the context of a macro. I can workaround it though. It just makes things more complex.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.