Mutating a container while having immutable borrows of the contents

This is a follow-on question to https://www.reddit.com/r/learnrust/comments/uqgr4e/hoping_for_feedback_on_snippet_exercism_forth/ although it probably isn't necessary to look at the prior post.

I'm trying out some different patterns for managing my Vec<String>s and iterators rather than trying to have the iterators own the strings.

Is there a pattern where I can immutably borrow elements in a container that can have new items added to it?

As an example, imagine (or refer to the link above) a loop over a chain of iterators. New items can be added and chained in from Vec<String>'s, which I need to store to ensure their lifetime. This means that there's an immutable borrow against the Vec<String>, but I also need to be able to add new Vec<Strings> as I go.

error[E0502]: cannot borrow `used_definitions` as mutable because it is also borrowed as immutable
  --> src\exercism_forth.rs:73:21
   |
73 |                     used_definitions.push(extra);
   |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
74 |                     stream = Box::new(used_definitions.last().unwrap().iter().chain(stream));
   |                                       -----------------------                       ------ immutable borrow later used here
   |                                       |
   |                                       immutable borrow occurs here

I'm not exactly sure if a Cell is something that solves this... cells allow interior mutability, but do they prevent a container from being borrowed immutably by borrowing the contents of an item immutably?

Thanks!

Posted May 18, 2022, 2:48 AM UTC

13
monkChuck105•

You can simply iterate over the indices, ie 0 .. len, while pushing items into the end of the vec. It's not ideal, but it should be fine.

2
Redundancy_OP•

In theory, I think I could use Bumpalo::Bump as allocation into an arena does not require &mut self of the arena itself, which gives me a way to hold ownership of a number of immutable Vec<String> objects as I iterate over them.

I'm at least going to try that out, although I'm hoping for a simpler answer.

1
Redundancy_OP•

Fwiw, this actually worked and allowed my iterators to be Box<dyn Iterator<Item=&String>>while a Bumpalo:Bump holds ownership of the strings.

                    ...
                    self.definitions.insert((*def_word).clone(),items);
            },
            x if self.definitions.contains_key(x)  => {
                // ensure that stream iterates over objects owned by the bumpalo arena
                // this ensures that the mutable borrow to insert new definitions above is valid
                let d: &[String] = arena.alloc_slice_clone(&self.definitions[x]);
                stream = Box::new(d.iter().chain(stream));
            },

Since stream is not immutably borrowing from self.definitions but from the Bump, I can then mutably borrow to add a new definition. As a downside, if a definition is used more than once, I have multiple clones of it in a bump allocator.

1
Redundancy_OP•

Adding another bit of info in case anyone searches, but the elsa crate provides append only containers where you can add elements without a mutable borrow.

1