Suppose that I'm going through a vector (not necessarily linearly, so I can't just use map) and I need to change an element when it satisfies some condition. I would think to use some variable to keep track of where I am, for example, something like a current variable
let mut v = vec![1, 2, 3, 4];
let mut current = &mut v[0];
and then check current to for some condition to see if it needs to be changed. However, when I do
current = &mut v[1];
It gives me the cannot borrow v as mutable more than once at a time.
I feel like this should be allowed, since I've only used one variable, and I can't access the old borrow any more.
Is there some way I can let rust know that I'm giving the first borrow back, so I'm not borrowing twice? Or have I been thinking about this wrong, and there is a different rust idiom I should use? I've solved this problem by using the indeces for the vector instead of a mutable reference, but I think this problem of "traversing using a current and then changing it" goes beyond just vectors. What if the data structure I had didn't have indeces?