I have written the following code:
use fancy_regex::{Regex, Captures};
/// Returns an iterator with all captures of named groups
/// whose names match `predicate`
fn pairs<'a>(regex: &'a Regex, captures: &'a Captures, predicate: &'a fn (&str) -> bool) -> impl Iterator<Item=(String, String)> + 'a {
regex.capture_names()
.zip(&mut captures.iter())
.filter_map(|(name_opt, match_opt)| {
if let (Some(name), Some(match_)) = (name_opt, match_opt) {
if predicate(&name) {
let pair = (
name.to_string(),
match_.as_str().to_string()
);
return Some(pair);
}
}
None
})
}
Error message:
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:6:5
|
6 | / regex.capture_names()
7 | | .zip(&mut captures.iter())
| | --------------- temporary value created here
8 | | .filter_map(|(name_opt, match_opt)| {
9 | | if let (Some(name), Some(match_)) = (name_opt, match_opt) {
... |
18 | | None
19 | | })
| |______^ returns a value referencing data owned by the current function
|
= help: use `.collect()` to allocate the iterator
This is my second day with Rust, so I’m still mostly winging it:
- I’m unsure about the lifetime annotation
'a
but it made several compiler errors go away. - The Iterator method
.filter()
has a relatively complex type (MutFn
etc.) for its callback which makes me wonder if the type ofpredicate
is OK. - IINM,
.collect()
returns a collection so I’m not sure how it would help. - I tried
.clone()
at the end but that didn’t work either.
Any help welcome, thanks!