xxxxxxxxxx
Until now, we’ve not talked about global variables, which Rust does support but can be problematic with Rust’s ownership rules. If two threads are accessing the same mutable global variable, it can cause a data race.
'static lifetime, which means the Rust compiler can figure out the lifetime and we aren’t required to annotate it explicitly. Accessing an immutable static variable is safe.
xxxxxxxxxx
Functions declared within extern blocks are always unsafe to call from Rust code.
The reason is that other languages don’t enforce Rust’s rules and guarantees, and Rust can’t check them, so responsibility falls on the programmer to ensure safety.
he "C" part defines which application binary interface (ABI) the external function uses: the ABI defines how to call the function at the assembly level.
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
xxxxxxxxxx
Another use case for unsafe is implementing an unsafe trait.
A trait is unsafe when at least one of its methods has some invariant that By using unsafe impl, we’re promising that we’ll uphold the invariants that the compiler can’t verify.
We can declare that a trait is unsafe by adding the unsafe keyword before trait and marking the implementation of the trait as unsafe too
{
Sync and Send are examples of unsafe traits.
}
unsafe trait Foo {
// methods go here
}
unsafe impl Foo for i32 {
// method implementations go here
}
fn main() {}