0

I am giving a mutable reference of a Vec to an Iterator, so it can add Elements to it while just keeping an index of the Element. Thus after the Iterator being "used" shouldn't then the Vec be able to be referenced again?

(Here a link to a Rust playground example)

struct MyElement{
    category_index: usize,
    ...
}

impl MyElement{
    fn iter_from_src<'a>(source: &'a str, categories: &'a mut Vec<&'a str>)
      -> impl Iterator< Item = MyElement > {
        ...
        std::iter::from_fn(move || -> Option<MyElement> {
            ... //some iterator logic
            let category = find_category_in_source(source);
            if let Some(index) = categories.iter().position(|c| *c == category) {
                //no reference of categories is given to MyElement exept of the index
                Some( MyElement{ category_index: index, ... } )
            } else {
                let index = categories.len();
                // the only mutable usage of categories
                categories.push(category);

                Some( MyElement{ category_index: index, ... } )
            }

        })
    }
}

fn main() {
    let source: String = get_source();
    let mut categories = Vec::with_capacity(32);
    let mut elements = Vec::with_capacity(1024);
    
    for element in MyElement::iter_from_src(&source, &mut categories) {
        elements.push(element);
    }

    ...
    // error occurs here
    println!("{categories:#?}");

}

and there is no difference in using

let elements = MyElement::iter_from_src(&source, &mut categories).collect();

instead of the for-loop.

Eitherway the compiler Refuses:

error[E0502]: cannot borrow `categories` as immutable because it is also borrowed as mutable
  --> src/main.rs:81:16
   |
74 |     for element in MyElement::iter_from_src(&source, &mut categories) {
   |                                                      --------------- mutable borrow occurs here
...
81 |     println!("{categories:#?}");
   |                ^^^^^^^^^^
   |                |
   |                immutable borrow occurs here
   |                mutable borrow later used here

I am pretty new to rust so it can just be me understanding a concept wrong.

Still: Why does this throw an error?

And how can it be made possible, that the categories can not be referenced while the Iterator exists though they can afterwards?

Emmmmllll
  • 21
  • 2
  • This would be much easier to look into if you had a link to a Rust playground snippet that actually shows this behavior. – Sebastian Redl Jul 05 '23 at 18:27
  • Sorry i had a few typos in the code of my question. This [Rust playground snipped](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=396a54602a28908a86e932560c14b575) shows the behaviour. – Emmmmllll Jul 05 '23 at 18:47
  • Does this answer your question? [Why does this mutable borrow live beyond its scope?](/q/66252831/2189130) Don't use the same lifetime in two places for `&'a mut Vec<&'a str>` make two separate lifetimes. – kmdreko Jul 05 '23 at 19:02
  • Like so: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1b90a0aa567174b058ba72a96b808812 – kmdreko Jul 05 '23 at 19:12
  • Thanks, @kmdreko that solves it. And sorry again: I have read multiple similar questions (though not the one you showed me) and didn't know it was a duplicate. – Emmmmllll Jul 05 '23 at 19:29
  • No need to be sorry about duplicates, its hard for inexperienced users to know what they need if they don't even know what to search for – kmdreko Jul 05 '23 at 19:42
  • Also the more (differently worded) questions that are marked as duplicates of some canonical version, the easier that it will be for people to find in the future. Duplicate questions aren't a bad thing; they're part of how StackOverflow is supposed to work. – eggyal Jul 05 '23 at 20:05

0 Answers0