capypad
0 day streak
rust / intermediate
Snippet

Unsafe Rust: Working with Raw Pointers

Unsafe Rust gives you five additional superpowers: dereference raw pointers, call unsafe functions, implement unsafe traits, mutate static variables, and access union fields. Raw pointers (`*const T` and `*mut T`) can bypass Rust's borrow checker but require manual safety guarantees from the programmer.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
fn main() {
// Creating raw pointers is safe, dereferencing is unsafe
let mut value = 42;
 
// Create immutable and mutable raw pointers
let ptr1: *const i32 = &value as *const i32;
let ptr2: *mut i32 = &mut value as *mut i32;
 
unsafe {
// Read through raw pointer
println!("Value via immutable pointer: {}", *ptr1);
 
// Modify value through mutable raw pointer
*ptr2 = 100;
println!("Value after modification: {}", *ptr2);
 
// Call unsafe function
unsafe_fn();
 
// Work with foreign raw pointer (from C library simulation)
let foreign_data = vec![1i32, 2, 3, 4, 5];
let foreign_ptr = foreign_data.as_ptr();
println!("Foreign data first element: {}", *foreign_ptr);
}
 
// Unsafe function definition
unsafe fn unsafe_fn() {
println!("Called from unsafe context");
}
 
// Unsafe trait implementation
unsafe trait UnsafeTrait {
fn required_method(&self);
}
 
unsafe impl UnsafeTrait for Circle {
fn required_method(&self) {
println!("Implementing unsafe trait");
}
}
}
Breakdown
1
let ptr1: *const i32 = &value as *const i32;
Creating a raw immutable pointer - safe operation
2
*ptr2 = 100;
Dereferencing and writing through mutable raw pointer - unsafe operation
3
unsafe fn unsafe_fn()
Function marked unsafe - callers must be in unsafe block or mark call as unsafe
4
unsafe trait UnsafeTrait
Trait marked unsafe - implementations must be marked unsafe