53. element_offset — Find an Element's Index by Reference
Ever had a reference to an element inside a slice but needed its index? Before Rust 1.94, you’d reach for .position() with value equality or resort to pointer math. Now there’s a cleaner way.
The problem
Imagine you’re scanning a slice and a helper function hands you back a reference to the element it found. You know the reference points somewhere inside your slice, but you need the index — not a value-based search.
| |
You could call .position() with value comparison, but that re-scans the slice and compares by value — which is wasteful when you already hold the exact reference.
The solution: element_offset
<[T]>::element_offset takes a reference to an element and returns its Option<usize> index by comparing pointers, not values. If the reference points into the slice, you get Some(index). If it doesn’t, you get None.
| |
Why not .position()?
.position() compares by value and has to walk the slice from the start. element_offset is an O(1) pointer comparison — it checks whether your reference falls within the slice’s memory range and computes the offset directly.
| |
This distinction matters whenever your slice has duplicate values.
When the reference is outside the slice
If the reference doesn’t point into the slice, you get None:
| |
Clean, safe, and no unsafe pointer arithmetic required. Available since Rust 1.94.0.