Skip to content

drain() doc of vector (and others) is still unclear #92765

Closed

Description

The description of Vec::drain:

  • states that it "creates a draining iterator", leading to expectations that each iteration drains one element, that stopping the iteration should drain fewer elements because iterators are lazy (witnessed in Tracking issue for Vec::extract_if and LinkedList::extract_if #43244). The rest of the description counters that expectation, but by saying "when the iterator is dropped", there's again the suggestion that removal happens at that late stage. While conceptually it's simpler to state that the removal happens unconditionally and immediately, which corresponds to the verb "drain", like BinaryHeap::drain and HashMap::drain do.
  • says "unspecified how many elements are removed" if you circumvent dropping, which suggests it's only removing elements in the range like the rest of the text, but in reality the whole vector is slaughtered (Improve the documentation for Vec::drain #74652 clarified one aspect of this case but slightly muddled this one).
  • lists the possibility to use mem::forget as if that is just one of the ways to use the iterator, which makes the description harder to understand if you're not advanced in Rust.
  • does not say what happens to the elements removed but not yielded if the iterator is dropped before it is fully consumed. It makes most sense that they get dropped rather than leaked, but given what leeway Vec::drain grants itself elsewhere, it might be helpful to clarify. None of the other drain methods say this either (Perhaps improve the documentation of drain members further #93769). Vec::into_iter also doesn't but I believe the fact that the signature says it consumes the container implies it.

VecDeque::drain has the same issue (and got missed by #74652). String::drain probably too, it doesn't mention what may happen if you mem::forget the iterator.

@rustbot label A-collections A-docs C-enhancement T-libs-api

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-collectionsArea: `std::collection`A-docsArea: documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions