Function core::ptr::write1.0.0[][src]

pub unsafe fn write<T>(dst: *mut T, src: T)

Overwrites a memory location with the given value without reading or dropping the old value.

write does not drop the contents of dst. This is safe, but it could leak allocations or resources, so care must be taken not to overwrite an object that should be dropped.

Additionally, it does not drop src. Semantically, src is moved into the location pointed to by dst.

This is appropriate for initializing uninitialized memory, or overwriting memory that has previously been read from.

Safety

Behavior is undefined if any of the following conditions are violated:

Examples

Basic usage:

let mut x = 0;
let y = &mut x as *mut i32;
let z = 12;

unsafe {
    std::ptr::write(y, z);
    assert_eq!(std::ptr::read(y), 12);
}Run

Manually implement mem::swap:

use std::ptr;

fn swap<T>(a: &mut T, b: &mut T) {
    unsafe {
        let tmp = ptr::read(a);
        ptr::copy_nonoverlapping(b, a, 1);
        ptr::write(b, tmp);
    }
}

let mut foo = "foo".to_owned();
let mut bar = "bar".to_owned();

swap(&mut foo, &mut bar);

assert_eq!(foo, "bar");
assert_eq!(bar, "foo");Run