为什么在以下示例中显式声明了生命周期?

Why lifetime was explicitly declared in the following example?

我正在研究一些练习题的解决方案,但无法弄清楚为什么需要明确的生命周期声明?

#[derive(Debug)]
pub struct HighScores<'a> {
    scores: &'a [u32],
}

impl<'a> HighScores<'a> {
    pub fn new(scores: &'a [u32]) -> Self {
        HighScores { scores }
    }

    pub fn scores(&self) -> &[u32] {
        self.scores
    }

    pub fn latest(&self) -> Option<u32> {
        self.scores.last().cloned()
    }

    pub fn personal_best(&self) -> Option<u32> {
        self.scores.iter().max().cloned()
    }

    pub fn personal_top_three(&self) -> Vec<u32> {
        let mut res_vec = self.scores.to_vec();

        res_vec.sort_unstable_by(|a, b| a.cmp(b).reverse());
        res_vec.truncate(3);

        res_vec
    }
}

Source Exercism Exercise

这是由于 lifetime elision rules

考虑以下不工作 new fn:

pub fn new(scores: &[u32]) -> Self {
    HighScores { scores }
}
error[E0621]: explicit lifetime required in the type of `scores`

同于:

pub fn new(scores: &[u32]) -> HighScores<'a> {
    HighScores { scores }
}

返回 Self 与 return 您当前正在实现的类型 (HighScores<'a>) 相同,现在您的输入 &[u32] 有一个省略的生命周期不同于您的 return 类型中的显式生命周期,这对于您的示例结构是非法的。

还应注意,在您的 impl Header 中声明的生命周期不可用于函数输入的生命周期省略。

您可以通过设置输入的生命周期来解决此问题:

pub fn new(scores: &'a [u32]) -> Self {
    HighScores { scores }
}

或者省略输出生命周期:

pub fn new(scores: &[u32]) -> HighScores<'_> {
    HighScores { scores }
}