When I move a `match` statement from a closure into a fn, an error occurs

There are two testing functions from my repo (a public but unfinished project).

The first one (test1) passes.

And when I move the match statement from the closure into a function (see test2 and fn append) , here comes a trouble.

error: captured variable cannot escape `FnMut` closure body
   --> tests/extract.rs:149:37
147 |     let mut paragraphs = buf.split('\n');
    |         -------------- variable defined here
148 |     let output = events.into_iter()
149 |                        .map(|event| append(event, &mut paragraphs))
    |                                   - ^^^^^^^^^^^^^^^^^^^----------^
    |                                   | |                  |
    |                                   | |                  variable captured here
    |                                   | returns a reference to a captured variable which escapes t
he closure body
    |                                   inferred to be a `FnMut` closure
    = note: `FnMut` closures only have access to their captured variables while they are executing..
    = note: ...therefore, they cannot allow references to captured variables to escape

I don't know why test2 fails to compile.
Any explanation is appreciated.

I don't have time to reproduce and test this right now, so this is just an educated guess. Your function signature is:

pub fn append<'a, 'b: 'a>(event: Event<'a>, paragraphs: &'a mut impl Iterator<Item = &'b str>)
                          -> [Option<Event<'a>>; 3] {

You're returning the event passed in, so the Event<'a> should be the same; that looks fine. But you're (a) also returning data returned from the iterator -- i.e. from an Item -- and (b) the error is about returning the captured &mut paragraphs.

These lead me to believe that the item should match the events, not the reference to the iterator. Thus, try:

pub fn append<'a>(event: Event<'a>, paragraphs: &mut impl Iterator<Item = &'a str>)
                          -> [Option<Event<'a>>; 3] {
1 Like

Thank you very much! This compiles.

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.