I have a vector about which I know it contains an index i
(in this case 0
). I need the i
-th element of this vector and I don't care about the rest of the vector.
I could do:
#[derive(Debug)]
struct X(i32);
fn main() {
let x = vec![X(1), X(2), X(3)][0];
println!("x = {:?}", x);
};
But this doesn't compile.
So I could do:
let x = vec![X(1), X(2), X(3)].remove(0);
But remove
is O(n), maybe it'll get optimized out or maybe not, so I don't like the idea of calling it, while I don't mean to remove anything, since I don't care about the rest of the vector anyway.
Just to be sure about complexity, I could do:
let x = vec![X(1), X(2), X(3)].swap_remove(0);
But this doesn't seem to convey the intention very well.
Then there's .into_iter().next().unwrap()
if I'm only interested in the first element, .pop().unwrap()
if I want the last one, or .into_iter().nth(i).unwrap()
, in general.
But all of them seem very verbose. Is there anything that more clearly states the intention while being optimal?