Skip to content

Potential specialisation: DoubleEndedIterator::last #41691

Closed
@clarfonthey

Description

@clarfonthey

Right now, Iterator::last defaults to:

let mut last = None;
for x in self { last = Some(x); }
last

If the iterator implements DoubleEndedIterator, it should default to:

self.next_back()

Many standard library types manually implement this specialisation, but a blanket implementation would be nice too!

Another potential specialisation for nth with DoubleEndedIterator and ExactSizeIterator:

if self.len() - n < n {
    for x in self.rev() {
        if n == 0 { return Some(x) }
        n -= 1;
    }
} else {
    for x in self {
        if n == 0 { return Some(x) }
        n -= 1;
    }
}
None

There's a bunch of stuff here and it might be worth looking into what extra implementations the standard library has, and how we could potentially make this default using specialisation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions