std-method
Measure element distance with offset_from
offset_from yields a signed difference in elements, for compatible pointers into the same allocation (or permitted equal-address cases). The byte distance must meet the API requirements and divide exactly into the element size. Zero-sized pointees are not supported. Use indices when available instead. Expected stdout (not executed): 4 Common mistake: Subtracting addresses of independently allocated objects using offset_from.
Formal Syntax & Structure
rust syntaxrust
unsafe { end.offset_from(start) }Working Example
Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() { let items = [3_u16, 5, 7, 9]; let start = items.as_ptr(); // SAFETY: both pointers come from the same live array; end is one-past. let end = unsafe { start.add(items.len()) }; let length = unsafe { end.offset_from(start) }; println!("{length}");}