#How does 'a help avoid this error here?

6 messages · Page 1 of 1 (latest)

cunning fog
#

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?

lavish oriole
#

You have an awkward restriction here in that the iterator's type stops making sense after 'a expires

#

So you can't keep the iterator around after that

#

So you need a trait object that doesn't claim it can last "as long as you want" (aka 'static) but is instead bound by 'a

river finch
#

Also note that the function signature is odd: It allows the caller to specify which lifetime they want. Therefore, your function must be able to provide a value that's valid for any lifetime, including 'static.
Meaning, you might as well write

fn func<T>(item: i32) -> Box<dyn Iterator<Item = SomeStruct<'static>>>  {
    ...
}