lotsoftools

Understanding Rust Error E0133: Unsafe Code Outside Unsafe Block

What is Rust Error E0133?

Rust Error E0133 occurs when unsafe code is used outside of an unsafe block. This is disallowed because it can lead to potential dangers and bypass the safety checks that Rust enforces.

Examples of Unsafe Operations:

Unsafe operations in Rust include dereferencing raw pointers, calling functions via the Foreign Function Interface (FFI), and calling functions marked as unsafe.

An Erroneous Code Example:

unsafe fn f() { return; }

fn main() {
    f(); // error: call to unsafe function requires unsafe function or block
}

Fixing Rust Error E0133:

To fix Rust Error E0133, you need to enclose the unsafe code inside an unsafe block. This relaxes safety checks for that specific block, allowing the unsafe code to run without any issues.

Corrected Code Example:

unsafe fn f() { return; }

fn main() {
    unsafe { f(); } // ok!
}

Unsafe Code in Functions:

Though unsafe code is currently accepted within unsafe functions, it is no longer recommended. Instead, use unsafe blocks within these functions. This practice is in line with Rust's unsafe_op_in_unsafe_fn lint which is currently set to allow but will be upgraded to warn in future editions.

Updated Code Example:

unsafe fn f() { return; }

unsafe fn g() {
    f(); // Is accepted, but no longer recommended
    unsafe { f(); } // Recommended way to write this
}

Additional Resources:

For more information on unsafe code in Rust, refer to the Unsafe Rust section of the Rust book.

Recommended Reading