e027: Trust Me; I Promise!

Published: Dec. 1, 2018, 4:46 a.m.

b'

An intro to unsafe Rust and Rust\\u2019s idea of safety.

\\n

Show Notes

\\n

Errata

\\n

A quick correction: on the show I said that a trait needed to be unsafe when it had an unsafe fn method. This isn\\u2019t 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!

\\n
trait ASafeTrait {\\n    unsafe fn unsafe_method() {}\\n}\\n\\nunsafe AnUnsafeTrait {}
\\n

The idea of an unsafe trait is that it has some conditions which you must uphold to safely implement it \\u2013 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.

\\n

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

\\n\\n\\n

Examples

\\n

Borrow-checked code in unsafe

\\n
let mut f = String::from("foo");\\n\\nunsafe {\\n    let borrowed = &mut f;\\n    let borrow_again = &f;\\n\\n    println!("{}", borrowed);\\n\\n    // This would be unsafe and throw an error:\\n    // println!("{}", borrow_again);\\n}
\\n

(See it in a playground)

\\n
Safely mutating a raw pointer
\\n
let f = Box::new(12);\\nlet mut g = Box::into_raw(f);\\ng = &mut (g + 10);
\\n

(See it in a playground)

\\n

Sponsors

\\n

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

\\n

Patreon Sponsors

\\n\\n

(Thanks to the couple people donating who opted out of the reward tier, as well. You know who you are!)

\\n

Become a sponsor

\\n\\n

Contact

\\n'