Iterate through a vector of another structure


I have no idea, how i can do this.
I wrote a little example with the problem… Can anyone help me and describe what i did wrong?

Thanks for every help!


See if reading this and linked threads helps.


Thanks, but this looks really complex.
I need to learn more about the borrowing concept.
I know how i can to this in C++, Java and etc. but Rust is complete different.
I don’t understand the problem, why the compiler say…

for point in self.path_builder.points {
| ^^^^ cannot move out of borrowed content

I think… :smiley: I don’t try to move self out of the borrowed content, I try to get the points from the path_builder.


Yeah, this is because the dot operator automatically dereferences to the underlying value, and the compiler thinks you want to consume the points field (ie move it, rather than borrow it) but you only have a borrow of self (and thus all data it owns, such as points). The compiler thinks this because a Vec can be iterated by value (consuming it in the process) or by reference, and it’s picking by-value in the syntax you used.

The fix for this is simply for point in &mut self.path_builder.points { ... } (you can also use for point in self.path_builder.points.iter_mut()). But now you’re going to hit the problem that I thought you were asking about, which is you’ve mutably borrowed a part of self yet want to call a method on self that also requires a mutable borrow. Approaches to working around this is what that linked thread is about.


Thanks, this description is perfect!
Now i understand what the problem is and what you mean.
I don’t know how i can fix the second problem, but i try to solve this with the linked thread. :slight_smile:


You can make do_something an associated function instead of a method. But it’s hard to say more without knowing your real code (or an example closer in spirit).

The gist is you want the compiler to see that you’re borrowing disjoint fields of your struct, which it allows. But once you throw a method into the mix, it can no longer see that the method only borrows a disjoint subset of self (assuming that’s true) - it has to assume all of self is borrowed.


Yeah, this is the problem i need self in the “do_something” method.
I did a new example, i replaced the “do_something” method with a similar method that i need.



As an aside, you have some odd uses of unsafe but we can leave that for a separate discussion if you’re interested :slight_smile:.


Yes, few unsafe code. :sweat_smile:
I know how i can do this in C++ correct, but in Rust i’m a newbie.
But i like Rust and the idea behind it. I know a lot about low level graphic programming, so i try to support a few OpenSource Rust projects. The only problem now is, i need to learn a lot more about Rust.

Now it is late so i try to change this later… :slight_smile:
Really thanks you!
You have been a great help.