Skip to content

Add Default impls for iterators and adapters #77

Closed
@the8472

Description

@the8472

Proposal

Problem statement

Currently many iterators don't implement Default which means one can't derive(Default) structs containing them, mem::take() or Cell::take them.

Motivation, use-cases

https://github.com/rust-lang/rust/blob/dc2d232c7485c60dd856f8b9aee83426492d4661/library/alloc/src/vec/drain.rs#L129

        let iter = mem::replace(&mut self.iter, (&mut []).iter());

could be replaced with

        let iter = mem::take(&mut self.iter);

Solution sketches

Iterator sources should implement Default when it is unambiguous that the default should be an empty iterator. Examples:

  • slice::Iter{Mut}
  • vec::IntoIter
  • iter::Empty (already implements it)
  • btree_map::Iter
  • etc.

Adapters should implement it when the inner iterator does and when they don't have any closure that would have to be materialized

  • Skip<I> where I: Default
  • Flatten<I> where I: Default
  • Chain<A, B> where A: Default, B: Default

Examples where it should not be implemented

  • array::IntoIter since one could expect [T; N]::default().into_iter() where T: Default
  • iter::Once since one could expect iter::once(Default::default())
  • adapters::Map since it would require summoning an FnMut ex nihilo

Links and related work

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)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