0

I would like to get a slice of references from a vector which contains all but the Nth element. In my specific case, I would like a mutable reference to the Nth element and non-mutable references to all other elements.

I've got something that works but it results in some messy code.

let len = vector.len();
for index in 0..len {
    let (before, after_inclusive) = vector.split_at_mut(index);
    let (element_slice, after) = after_inclusive.split_at_mut(1);
    let element = &mut element_slice[0];
    let others = [before, after].concat();
    element.operation(&others);
}

Ideally, I would want a function that works something like this:

let (element, others) = vector.extract_split(index);

Or maybe some mode advanced slice syntax:

let others = vector[0..index, (index+1)..len]

Is there some library or cleaner bit of code that can do this?

For reference, the intent is to modify the position of an object in relation to all other objects. The loop acts as a basic collision detection system within a game.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Chuck
  • 431
  • 4
  • 10
  • 1
    Your solution is the correct one, although I wouldn't do the `concat`. Instead, I'd [`chain`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.chain) the `before` / `after` iterators. – Shepmaster Sep 02 '20 at 19:40
  • 1
    You could [create an extension trait](https://stackoverflow.com/q/33376486/155423) to wrap up your code so you could call it as `.extract_split(...)` as well. – Shepmaster Sep 02 '20 at 19:47
  • Thanks, I will look into extension traits. That would actually let me clean up other parts of my code as well. – Chuck Sep 02 '20 at 19:59

0 Answers0