I was playing around with iterators, when I came across an error.
Using the following code
fn func<'a, T>(item: i32) -> Box<dyn Iterator<Item = SomeStruct<'a>> + 'a> {
if item > 0 {
Box::new(once(SomeStruct(&1)))
} else {
Box::new(empty())
}
}
struct SomeStruct<'a>(&'a i32);
I get this error:
error: lifetime may not live long enough
--> src/main.rs:6:5
|
4 | fn func<'a>(item: i32) -> Box<dyn Iterator<Item = SomeStruct<'a>>>
| -- lifetime `'a` defined here
5 | {
6 | / if item > 0 {
7 | | Box::new(once(SomeStruct(&1)))
8 | | } else {
9 | | Box::new(empty())
10 | | }
| |_____^ returning this value requires that `'a` must outlive `'static`
By adding + 'a to the return type signature, the error goes away:
-> Box<dyn Iterator<Item = SomeStruct<'a>> + 'a>
How is adding + 'a solving the error here?