What is Unsafe?
- There can be 2 types of Rust.
Safe Rust | Unsafe Rust (Like C Programming language) | |
---|---|---|
Memory safety |
Guarantees enforced at compile time, ie Compiler takes care of type-safety, memory-safety, thread safety etc |
Like C, Compiler does not check safety rules and coder does at its own risk Eg: In unsafe code you can dereference null pointer at your own risk |
5 Things | Not allowed |
Unsafe superpowers: 1. Dereference a raw pointer 2. Call an unsafe function or method 3. Access or modify a mutable static variable 4. Implement an unsafe trait 5. Access fields of a union |
How to be implemented | Access to unsafe code should be done via safe API |
Why we need Unsafe Rust
-
Underlying computer hardware is inherently unsafe, if unsafe operations are not allowed, Rust programmers
couldn’t do certain tasks. Eg: Writing device drivers, Interaction with OS, or Writing own OS
Maybe you're writing a low-level abstraction not exposed by the standard library.