How to transfer several elements from a collection to a function with one or more of the elements to be changed?

When two elements are transferred from the same vector to a function, the borrowing controller will not allow changing one of the elements.

struct Point { x: i32, y: i32, } fn main() { let mut vec: Vec<Point> = Vec::new(); foo(&mut vec[0], &vec[1]); } fn foo(pnt_1: &mut Point, pnt_2: &Point) { } 

error: cannot take vec as immutable, as it is also borrowed as mutable

vec never borrowed by foo , although vec[0] borrowed and vec[0] is Point .

How to transfer several elements from one collection to a function with one or more mutable elements?

+5
source share
1 answer

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.

+7
source

Source: https://habr.com/ru/post/1257464/


All Articles