How struct has two life times


#1

While I was trying to make some tweaks on Rust Book examples

#[derive(PartialEq, Debug)]
pub struct Shoe<'a>{
    pub size: u32,
    pub style: &'a str,
}

pub fn shoes_in_my_size(shoes: &[Shoe], size: u32) -> Vec<&Shoe> {
    shoes.iter().filter(|s| s.size == size).collect()
}

But when I run this I get from which I can see that Shoe has 2 lifetimes but I can’t understand how or how to solve it

error[E0106]: missing lifetime specifier
 --> src/lib.rs:7:59
  |
7 | pub fn shoes_in_my_size(shoes: &[Shoe], size: u32) -> Vec<&Shoe> {
  |                                                           ^ expected lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say which one of `shoes`'s 2 lifetimes it is borrowed from

error[E0106]: missing lifetime specifier
 --> src/lib.rs:7:60
  |
7 | pub fn shoes_in_my_size(shoes: &[Shoe], size: u32) -> Vec<&Shoe> {
  |                                                            ^^^^ expected lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say which one of `shoes`'s 2 lifetimes it is borrowed from

error: aborting due to 2 previous errors

error: Could not compile `iterators`.

#2

The struct has one lifetime parameter but you’re accepting and returning a reference with its own lifetime - that’s where the 2 comes from.

The simplest solution for your case is:

pub fn shoes_in_my_size<'a>(shoes: &'a [Shoe<'a>], size: u32) -> Vec<&'a Shoe<'a>> {
    shoes.iter().filter(|s| s.size == size).collect()
}