0

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?

Michał Trybus
  • 11,526
  • 3
  • 30
  • 42
  • I'd use `swap_remove()` or `into_iter().nth()`. – Chayim Friedman May 04 '23 at 14:11
  • 2
    Of course, if you feel this doesn't convey the intention well or is too verbose, just create a function with a proper name with that as body. – Chayim Friedman May 04 '23 at 14:14
  • @ChayimFriedman on second thought I'm actually hesitating between `swap_remove` and `into_iter().nth()` now. The latter is nice, because `into_iter` conveys the intention of dropping the vector, while `nth` should be O(1), I assume. – Michał Trybus May 04 '23 at 14:25
  • 2
    `nth()` is O(1) with `std::vec::IntoIter`. If the code is really hot (enough to do micro-optimizations, and even then I'm not sure this will be noticable - the deallocation will likely take more time anyway) then for types that implement `Drop` `swap_remove()` is likely to be a bit faster, and for big types `into_iter().nth()` is likely to be a bit faster. And for big types implementing `Drop`? I don't know, measure. – Chayim Friedman May 04 '23 at 14:28

0 Answers0