Skip to content

Methods get and split_at* are reducing slice's lifetime #45

Description

@akhilman

I believe all methods that return sub-slices of SliceRef and SliceMut, including .idx, .get, and all variations of .split_at, should yield slices with the same lifetime as the original slice, just like standard slices do.

Take a look following iterator:

struct BatchIterator<'a, T> {
    batch_size: usize,
    data: &'a [T],
}

impl<'a, T> Iterator for BatchIterator<'a, T> {
    type Item = &'a [T];

    fn next(&mut self) -> Option<Self::Item> {
        let (batch, remaining) = self.data.split_at(self.batch_size.min(self.data.len()));
        self.data = remaining;
        if batch.is_empty() { None } else { Some(batch) }
    }
}

Similar iterator is not possible with SliceRef/SliceMut right now because split_at reduces lifetime to the current scope.

Only solutions I have in mind right now is to move the implementations of .get and .split_at* to SliceRef<'a,T> and SliceMut<'a,T> to preserve 'a lifetime. Or, we could introduce an additional wrapper with correct lifetime between SliceRef/SliceMut and the owned Slice, applying all methods to this new wrapper.

I'm willing to contribute to resolve this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions