Search code examples
rusttraitsborrow-checker

Implement trait for slice with lifetime bound from function parameter


In the following snippet, I'm trying to implement 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]
    }
}

This doesn't work however, because the borrow-checker (rightfully) complains that the lifetime for the outer &[f32] doesn't match with the lifetime of slice. How do I express this, preferably without changing the trait?

I've tried the following, but without result:

// 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]
    }
}

Solution

  • How about making Get generic over the lifetime '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]
        }
    }