advancedUnsafe
Unsafe Traits
Define and implement unsafe traits.
Unsafe Traits
Define and implement unsafe traits.
Difficulty
Advanced
Code
rust
unsafe trait Dangerous {
fn dangerous_method(&self);
}
struct MyType {
value: i32,
}
unsafe impl Dangerous for MyType {
fn dangerous_method(&self) {
println!("calling dangerous method on {}", self.value);
}
}
fn take_dangerous<T: Dangerous>(item: &T) {
item.dangerous_method();
}
fn main() {
let x = MyType { value: 42 };
take_dangerous(&x);
}Explanation
Unsafe traits have invariants the compiler cannot verify.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the unsafe category to build a complete understanding of this topic.