This isn’t the first time that I difficulties understanding how I should re-write my code to please the borrow checker when I try to take two references (and at least one of them being mutable) to different elements of the same vector (or any other container for that matter).
Basically, what I’m trying to do is to access mutably to an element of a vector, based on the value of another element of the same vector, where the index of both elements aren’t the same (otherwise the code must panic).
let mut elements = vec![2, 1, 1]; let v1 = &elements; // take a reference to the element at index 0 assert!(v1 != 0); let v2 = &mut elements[*v1]; // this doesn’t compile /* ... (modify v2) */
Not that the element are not
Copy in my real code, hence why I need to take a reference for
I don’t understand why there isn’t some kind of
punch_hole(container, index) function in std that would return a mutable reference to the element at the
index in the
container alongside a mutable "view" of the container where we can access all the element but the one at
index (ie. trying to access the element at the index of the hole would panic).
I did an experimental implementation on the [Rust Playground) for
Vec<T>. A similar logic could be used to implement it for any other containers.