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

unsafe allows raw pointers and unsafe operations.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

More Unsafe Examples