为具有从函数参数绑定的生命周期的切片实现特征

Implement trait for slice with lifetime bound from function parameter

在下面的代码片段中,我试图实现 C:

// A
trait Get {
    fn get(slice: &[f32]) -> Self;
}

// B
impl Get for () {
    fn get(slice: &[f32]) -> Self {
        ()
    }
}

// C
impl Get for &[f32] {
    fn get(slice: &[f32]) -> Self {
        &slice[0..5]
    }
}

但这不起作用,因为借用检查器(理所当然地)抱怨外部 &[f32] 的生命周期与 slice 的生命周期不匹配。我如何表达这一点,最好不要改变特征?

我尝试了以下方法,但没有结果:

// Doesn't work because the function signature differs from the Trait
impl<'a> Get for &'a [f32] {
    fn get(slice: &'a [f32]) -> Self {
        &slice[0..5]
    }
}

// Doesn't work, because the trait bound is not the same as the trait function
impl<'b> Get for &'b [f32] {
    fn get<'a>(slice: &'a [f32]) -> Self where 'a: 'b {
        &slice[0..5]
    }
}

如何使 Get 在生命周期内通用 'a:

trait Get<'a> {
    fn get(slice: &'a [f32]) -> Self;
}

impl<'a> Get<'a> for () {
    fn get(slice: &'a [f32]) -> Self {
        ()
    }
}

impl<'a> Get<'a> for &'a [f32] {
    fn get(slice: &'a [f32]) -> Self {
        &slice[0..5]
    }
}