为什么我可以在一种情况下省略 return 类型的生命周期,而另一种情况则需要明确选择生命周期?

Why can I elide the lifetime of the return type in one case but another one requires to choose a lifetime explicitly?

在这里,我必须给App一个完整的生命,不能省略它(App<'_>):

struct App<'a> {
    items: StatefulList<'a, (&'a str, &'a str, usize)>,
}

impl App<'_> {
    fn new<'a>(items: &'a Vec<(&'a str, &'a str, usize)>) -> App<'a> {
        App {
            items: StatefulList::with_items(items),
        }
    }
}

如果我只指定外部的生命周期,它也有效 Vec:

fn new<'a>(items: &'a Vec<(&str, &str, usize)>) -> App<'a>

如果我尝试省略它,它给出 (playground):

error[E0106]: missing lifetime specifier
  --> src/lib.rs:18:53
   |
18 |     fn new(items: &Vec<(&str, &str, usize)>) -> App<'_> {
   |                   -------------------------         ^^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but the signature does not say which one of `items`'s 3 lifetimes it is borrowed from
help: consider introducing a named lifetime parameter
   |
18 |     fn new<'a>(items: &'a Vec<(&str, &str, usize)>) -> App<'a> {
   |           ++++         ++                                  ~~

然而,对于 with_items 方法,我可以愉快地省略生命周期:

struct StatefulList<'a, T> {
    state: ListState,
    items: &'a Vec<T>,
}

impl<T> StatefulList<'_, T> {
    fn with_items(items: &Vec<T>) -> StatefulList<'_, T> {
        StatefulList {
            state: ListState::default(),
            items,
        }
    }
}

这是为什么?

编译器告诉你原因:

this function's return type contains a borrowed value, but the signature does not say which one of items's 3 lifetimes it is borrowed from

类型 &Vec<(&str, &str, usize)> 中有 三个 生命周期:&'a Vec<(&'b str, &'c str, usize)>。当有一个参数时,lifetime elision rules只能为return类型选择生命周期,或者如果有self参数,在这种情况下它们使用它的生命周期。