How to transfer several elements from one collection to a function with one or more mutable elements?
The short answer is that you cannot, at least not without the support of the collection itself.
Rust prohibits mutable aliases - multiple names for the same, one of which allows mutation.
It would be too difficult (with the current state of programming languages) to verify that (&mut vec[0], &vec[1]) does not introduce anti-aliasing, but (&mut vec[0], &vec[0]) does. Adding to the complexity is that the [] operator can be overloaded, which allows you to create a type such that foo[0] and foo[1] actually point to the same thing.
So how can a collection help? Each collection will have (or not have) a specific way of splitting in a safe anti-aliasing manner.
There may be methods like slice::split_at_mut that confirm that the two halves cannot intersect, and thus no aliases can occur.
Unfortunately, there is no HashMap::get_two_things(&a, &b) that I know of. It would be a pretty niche, but that does not mean that it cannot exist.
vec never borrowed by foo though
It certainly is. When you index vec , you get a link to some piece of memory inside vec . If vec was supposed to change under you, for example, when someone adds or removes a value, then reallocation of the base memory may be required, which will invalidate the link. This is a prime example of why mutable anti-aliasing is bad.
source share