Skip to content

implement Default for more iterators #656

@programmerjake

Description

@programmerjake

Proposal

Problem statement

Sometimes it's useful to be able to create empty iterators without needing to first obtain an empty container to then iterate over, some of the existing iterator types implement Default for this #77 but there are still quite a few missing.

Motivating examples or use cases

I'm currently writing a parser for parsing templates for command lines that are already split into a slice of arguments (written using the Default impls I'd like to add):

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Token {
    Char(char),
    ArgSeparator,
}

#[derive(Clone, Debug, Default)]
struct Tokens<'a> {
    current: std::str::Chars<'a>,
    rest: std::slice::Iter<'a, &'a str>,
}

impl<'a> Tokens<'a> {
    fn new(args: &'a [&'a str]) -> Self {
        Self { rest: args, ..Self::default() }
    }
}

impl Iterator for Tokens<'_> {
    type Item = Token;

    fn next(&mut self) -> Option<Self::Item> {
        match self.current.next() {
            Some(c) => Some(Token::Char(c)),
            None => {
                self.current = self.rest.next()?.chars();
                Some(Token::ArgSeparator)
            }
        }
    }
}

// code that uses Tokens...

Solution sketch

implement Default for all iterators where the iterator is constructed from some type that has an obvious default value that's empty. So std::str::Chars should be Default since "" is obviously empty. std::array::IntoIter should not be Default since the array type's default wouldn't be empty unless it has zero length. std::env::Args should not be Default since an obvious default value is the program's arguments which isn't usually empty.

The full list of iterator types: https://doc.rust-lang.org/nightly/std/iter/trait.Iterator.html#implementors

Iterator implementations I found:

iterator implements Default already

For list, see #656 (comment)

iterator should implement Default

iterator could implement Default but it might make the rest of the iterator slower (e.g. adding a conditional in Drop)

iterator shouldn't implement Default

iterator could implement Default but we maybe shouldn't

Alternatives

Manually construct iterators from a manually-obtained empty source type and have to implement Default manually.

Links and related work

We did some of this before in #77 but didn't end up handling all the iterator types.

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

  • We think this problem seems worth solving, and the standard library might be the right place to solve it.
  • We think that this probably doesn't belong in the standard library.

Second, if there's a concrete solution:

  • We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
  • We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions