#### Dereferencing a raw pointer Raw pointers can be immutable or mutable and are written as: * Immutable: *const T * Mutable: *mut T The asterisk isn’t the dereference operator; it’s part of the type name. Different from references and smart pointers, raw pointers: * Are allowed to ignore the borrowing rules by having both immutable and mutable pointers or multiple mutable pointers to the same location * Aren’t guaranteed to point to valid memory * Are allowed to be null * Don’t implement any automatic cleanup Example: ``` rust let mut num = 5; let r1 = &num as *const i32; let r2 = &mut num as *mut i32; unsafe { println!("r1 is: {}", *r1); println!("r2 is: {}", *r2); } ``` Another example which will likely lead to segmentation fault: ``` rust let address = 0x012345usize; let r = address as *const i32; ``` #### Calling an Unsafe Function or method Example: ``` rust unsafe fn dangerous() {} unsafe { dangerous(); } ``` The `unsafe` keyword in this context indicates the function has requirements we need to uphold when we call this function, because Rust can’t guarantee we’ve met these requirements. By calling an `unsafe` function within an unsafe block, we’re saying that we’ve read this function’s documentation and take responsibility for upholding the function’s contracts. #### FFI ``` rust extern "C" { fn abs(input: i32) -> i32; } fn main() { unsafe { println!("Absolute value of -3 according to C: {}", abs(-3)); } } ``` Within the `extern "C"` block, we list the names and signatures of external functions from another language we want to call. The `"C"` part defines which application binary interface (ABI) the external function uses: the ABI defines how to call the function at the assembly level. The "C" ABI is the most common and follows the C programming language’s ABI. #### Accessing or Modifying a Mutable Static Variable In Rust, global variables are called static variables. ``` rust static HELLO_WORLD: &str = "Hello, world!"; fn main() { println!("name is: {}", HELLO_WORLD); } ``` In the above example the variable type is `&'static str`. Since, static variables can only store references with the `'static` lifetime, you don't need to annotate it explicityly. ``` rust static mut COUNTER: u32 = 0; fn add_to_count(inc: u32) { unsafe { COUNTER += inc; } } fn main() { add_to_count(3); unsafe { println!("COUNTER: {}", COUNTER); } } ``` #### Implementing an Unsafe Trait A trait is unsafe when at least one of its methods has some invariant 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. ```