Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of an element in a vector using pointer arithmetic?

In C you can use the pointer offset to get index of an element within an array, e.g.:

index = element_pointer - &vector[0];

Given a reference to an element in an array, this should be possible in Rust too.

While Rust has the ability to get the memory address from vector elements, convert them to usize, then subtract them - is there a more convenient/idiomatic way to do this in Rust?

like image 657
ideasman42 Avatar asked Sep 02 '25 04:09

ideasman42


1 Answers

There isn't a simpler way. I think the reason is that it would be hard to guarantee that any operation or method that gave you that answer only allowed you to use it with the a Vec (or more likely slice) and something inside that collection; Rust wouldn't want to allow you to call it with a reference into a different vector.

More idiomatic would be to avoid needing to do it in the first place. You can't store references into Vec anywhere very permanent away from the Vec anyway due to lifetimes, so you're likely to have the index handy when you've got the reference anyway.

In particular, when iterating, for example, you'd use the enumerate to iterate over pairs (index, &item).

like image 94
Chris Emerson Avatar answered Sep 05 '25 01:09

Chris Emerson