Lifetime problem returning reference to existing or new element of container

The playground link Rust Playground contains two variants of a simple function.

The function is supposed to look up an element in a container. If the element doesn't exist, a new element should be added. In either case, a mutable reference to the element should be returned.

The first (commented out) variant is using a for i in 0..self.children.len() loop and is working. The second variant is using a for c in self.children.iter_mut() loop but is rejected by the borrow checker.

What would be an elegant way to make the second variant working?

It's a limitation of the current borrow checker. The next-generation borrow checker, Polonius, accepts it. If you search for "Polonius" in this forum, you will find other examples, such as this thread.

Here are two workarounds of varying inelegance based on those in the other thread.

3 Likes

Thanks a lot, @quinedot, this was helpful.

I had already found the solution via the raw pointer cast return unsafe { &mut *(c as *mut _) } myself, but I didn't realize that such an ugly solution might indeed be justified, because there really is a known limitation in the current borrow checker which prevents a clean solution and needs to be worked around.

Following your links, I've found Baby Steps which contains a code example of this problem reduced to its minimum.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.