I want to write a closure that takes an object and returns an iterator from it. The idea is to store the closure in a structure and apply as needed:

fn main() { let iter_wrap = |x: &String| Box::new(x.chars()); let test = String::from("test"); for x in iter_wrap(&test) { println!("{}", x); } }

This causes the error:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements --> src/main.rs:2:45 | 2 | let iter_wrap = |x: &String| Box::new(x.chars()); | ^^^^^ | note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 2:21... --> src/main.rs:2:21 | 2 | let iter_wrap = |x: &String| Box::new(x.chars()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...so that reference does not outlive borrowed content --> src/main.rs:2:43 | 2 | let iter_wrap = |x: &String| Box::new(x.chars()); | ^ note: but, the lifetime must be valid for the call at 5:14... --> src/main.rs:5:14 | 5 | for x in iter_wrap(&test) { | ^^^^^^^^^^^^^^^^ note: ...so that argument is valid for the call --> src/main.rs:5:14 | 5 | for x in iter_wrap(&test) { | ^^^^^^^^^^^^^^^^

I tried to change String to Vec and remove boxing, but the result is the same.

How can I make it compile?