11

addr_of_mut

 3 years ago
source link: https://doc.rust-lang.org/stable/std/ptr/macro.addr_of_mut.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Macro std::ptr::addr_of_mut1.51.0[−][src]

macro_rules! addr_of_mut {
    ($place:expr) => { ... };
}

Create a mut raw pointer to a place, without creating an intermediate reference.

Creating a reference with &/&mut is only allowed if the pointer is properly aligned and points to initialized data. For cases where those requirements do not hold, raw pointers should be used instead. However, &mut expr as *mut _ creates a reference before casting it to a raw pointer, and that reference is subject to the same rules as all other references. This macro can create a raw pointer without creating a reference first.

Example

use std::ptr;

#[repr(packed)]
struct Packed {
    f1: u8,
    f2: u16,
}

let mut packed = Packed { f1: 1, f2: 2 };
// `&mut packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
let raw_f2 = ptr::addr_of_mut!(packed.f2);
unsafe { raw_f2.write_unaligned(42); }
assert_eq!({packed.f2}, 42); // `{...}` forces copying the field instead of creating a reference.
Run

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK