RRust By Example
advancedUnsafe

Unsafe Rust

Use unsafe blocks for raw pointer operations.

Unsafe Rust

Use unsafe blocks for raw pointer operations.

Difficulty

Advanced

Code

rust
fn main() {
    let mut num = 5;
    let r1 = &num as *const i32;
    let r2 = &mut num as *mut i32;

    unsafe {
        println!("r1: {}", *r1);
        *r2 = 10;
        println!("r2: {}", *r2);
    }

    println!("num: {}", num);
}

Explanation

This example demonstrates how to use unsafe rust in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the unsafe category to build a complete understanding of this topic.

More Unsafe Examples