61

Trust Me; I Promise! – An intro to unsafe Rust and Rust's idea of safety

 5 years ago
source link: https://www.tuicool.com/articles/hit/i2AV73a
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

A quick correction: on the show I said that a trait needed to be unsafe when it had an unsafe fn method. This isn't correct: safe traits can have unsafe methods, and unsafe traits can exist without any methods at all (as implied by my reference to Send and Sync ). You can see this in practice in the following example, which compiles just fine!

trait ASafeTrait {
    unsafe fn unsafe_method() {}
}

unsafe trait AnUnsafeTrait {}

The idea of an unsafe trait is that it has some conditions which you must uphold to safely implement it – again, just as with Send and Sync . In the case of most traits, this will be because some trait method has invariants it needs to hold else it would cause undefined behavior. For another example of this, see the (unstable as of the time of recording) trait std::iter::TrustedLen .

Thanks to Rust language team member @centril for noting this to me after listening when I was recording the show live!

Borrow-checked code in unsafe

let mut f = String::from("foo");

unsafe {
    let borrowed = &mut f;

    // This would be unsafe and throw an error (before Rust 2018):
    // let borrow_again = &f;

    println!("{}", borrowed);

    // This would be unsafe and throw an error:
    // println!("{}", borrow_again);
}

(See it in a playground)

Safely mutating a raw pointer

let f = Box::new(12);
let mut g = Box::into_raw(f);
g = &mut 10;

(See it in a playground)

Thanks to Parity for sponsoring the show again. Go check out their Rust jobs !


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK