Security off: Programming in Rust with `unsafe`


extern "C" {
    fn abs(enter: i32) -> i32;

fn primary() {
    unsafe {
        println!("Absolute worth of -3 based on C: {}", abs(-3));

Any calls made to the capabilities uncovered by way of the extern "C" block have to be wrapped in unsafe, the higher to make sure you take correct duty for what you ship to it and get again from it.

Altering mutable static variables

International or static variables in Rust might be set to mutable, since they occupy a set reminiscence handle. Nonetheless, it’s solely potential to switch a mutable static variable inside an unsafe block.

Information races are the largest cause you want unsafe to change mutable static variables. You’d get unpredictable outcomes in the event you allowed the identical mutable static variable to be modified from totally different threads. So, whereas you should use unsafe to make such modifications, any information race points could be your duty, not Rust’s. Generally, Rust can not completely forestall information races, however that you must be doubly cautious about that in unsafe blocks.