swap_remove might be just the thing. It'll efficiently swap in the last element in place of the one you're removing, saving a lot of shuffling for a Vec you're about to drop anyway.
The surrounding context is that I'm validating a JSON array and I need to return 1 invalid element as part of the error message (the Err path of the Result).
As @quinedot suggested it might, this results in two loops (one to drop the items before index and one for the items after)[1] â but that's merely duplicate machine code, not duplicate work at run time.
However, the difference between this and swap_remove() will be tiny unless size_of::<T>() is particularly large.
if T has a destructor; if it doesn't, no loops at all are needed âŠī¸
If there's no custom Drop, human intuition suggests that v.into_iter().nth(index) would iterate until index instead of accessing v[index] directly, resulting in O(n) complexity. Can we rely on the optimizer to turn it into O(1)?