rust / intermediate
Snippet
Dereferencing Raw Pointers in Unsafe Rust
Raw pointers (*const T and *mut T) allow you to bypass Rust's ownership and borrowing rules. Dereferencing them is considered unsafe because the compiler cannot guarantee the pointer is valid or that it doesn't violate memory safety.
snippet.rs
1
2
3
4
5
6
7
8
9
let mut num = 5;let r1 = &num as *const i32;let r2 = &mut num as *mut i32;unsafe {println!("r1 is: {}", *r1);*r2 = 10;println!("num is now: {}", num);}
Breakdown
1
let r1 = &num as *const i32;
Create an immutable raw pointer from a reference.
2
unsafe { ... }
Block required to perform operations that the compiler cannot verify as safe.
3
*r1
Dereferencing the raw pointer to access the value it points to.