Programming Languages
Rust
Subjective
Oct 04, 2025
Explain unsafe Rust and when it is necessary to use unsafe blocks.
Detailed Explanation
Unsafe Rust capabilities and usage:
• Dereference raw pointers
• Call unsafe functions or methods
• Access or modify mutable static variables
• Implement unsafe traits
• Access fields of unions
When unsafe is necessary:
• FFI (Foreign Function Interface)
• Low-level system programming
• Performance-critical optimizations
• Implementing safe abstractions
• Hardware interaction
• Custom allocators
Safety rules still apply:
• Memory safety is your responsibility
• Data race prevention
• Proper initialization
• Lifetime management
Example:
// Safe wrapper around unsafe operations
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
let ptr = slice.as_mut_ptr();
assert!(mid <= len);
unsafe {
(
std::slice::from_raw_parts_mut(ptr, mid),
std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
)
}
}
// FFI example
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
println!("Absolute value of -3: {}", abs(-3));
}
}
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts