Raw Pointers
unsafe, since they skip the usual safety checks.In this page:
Creating Raw Pointers
Raw pointers can be created from references using as *const T or as *mut T. Creating a raw pointer itself is completely safe -- only dereferencing it requires unsafe.
Example: Creating Raw Pointers
fn main() {
let value = 100;
let const_ptr = &value as *const i32;
println!("Pointer created (not yet dereferenced)");
unsafe {
println!("Value: {}", *const_ptr);
}
}
Login to try C/C++/Java/PHP code in the editor
Mutable Raw Pointers
*mut T allows modifying the pointed-to data through the pointer, but like all raw pointer dereferences, doing so requires an unsafe block.
Example: Mutable Raw Pointers
fn main() {
let mut value = 5;
let mut_ptr = &mut value as *mut i32;
unsafe {
*mut_ptr += 1;
}
println!("value = {}", value);
}
Login to try C/C++/Java/PHP code in the editor
Raw Pointers Skip Borrow Checking
Unlike references, you can have multiple raw pointers (even mutable ones) to the same data at once, since the borrow checker does not track raw pointers -- this is exactly why dereferencing them is unsafe.
Example: Raw Pointers Skip Borrow Checking
fn main() {
let mut number = 10;
let p1 = &mut number as *mut i32;
let p2 = &mut number as *mut i32;
unsafe {
*p1 += 1;
*p2 += 1;
}
println!("number = {}", number);
}
Login to try C/C++/Java/PHP code in the editor
Why Raw Pointers Exist
Raw pointers are essential for low-level tasks like foreign function interfaces (calling C code) and for building safe abstractions internally, where the implementer manually guarantees the safety invariants the compiler cannot check.
Example: Why Raw Pointers Exist
fn main() {
let array = [1, 2, 3, 4];
let ptr = array.as_ptr();
unsafe {
println!("First element via raw pointer: {}", *ptr);
println!("Second element via offset: {}", *ptr.offset(1));
}
}
Login to try C/C++/Java/PHP code in the editor
- Dereferencing a raw pointer outside of an
unsafeblock, which is a compile error. - Creating a raw pointer to data that has already gone out of scope, resulting in a dangling pointer that is legal to create but unsafe to dereference.
- Confusing
*const T(immutable raw pointer) with*mut T(mutable raw pointer) -- they have different capabilities.
*const Tand*mut Tare raw pointers that bypass Rust's normal borrowing rules.- Creating a raw pointer is safe; dereferencing one requires an
unsafeblock. - Raw pointers can be null, dangling, or unaligned -- Rust does not guarantee their validity the way it does for references.
- Raw pointers are mainly used for low-level interoperability (like FFI) and building custom safe abstractions.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: