How to Use std

:mem for Memory Operations

Use std::mem functions like swap, replace, and size_of to manage memory layout and value exchange efficiently in Rust.

Use std::mem functions to perform low-level memory operations like swapping values, replacing data, or checking type sizes without moving or copying data unnecessarily. The most common operations are std::mem::swap to exchange values, std::mem::replace to take ownership of a value while leaving a placeholder, and std::mem::size_of to determine memory usage.

use std::mem;

fn main() {
    let mut a = 5;
    let mut b = 10;

    // Swap values without temporary variables
    mem::swap(&mut a, &mut b);
    println!("a: {}, b: {}", a, b);

    // Replace 'a' with 0 and get the old value
    let old_a = mem::replace(&mut a, 0);
    println!("old_a: {}, a: {}", old_a, a);

    // Check size of an i32 in bytes
    let size = mem::size_of::<i32>();
    println!("Size of i32: {} bytes", size);
}