Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

A potential ambiguity concerning the alternate wording and the example usage of HashSet::retain. #106535

Closed
aalekhpatel07 opened this issue Jan 6, 2023 · 2 comments · Fixed by #106553
Assignees
Labels
A-docs Area: Documentation for any part of the project, including the compiler, standard library, and tools

Comments

@aalekhpatel07
Copy link

aalekhpatel07 commented Jan 6, 2023

Location

Lines 310-321 of std/collections/hash/set.rs

Summary

The alternate (and presumably simpler) wording says

"In other words, remove all elements e for which f(&e) returns false."

but the example usage in the doc comment would've compiled just fine even if we accidentally misread/misinterpreted that as "... returns true" (since the count of removed and retained items are equal):

let mut set = HashSet::from([1, 2, 3, 4, 5, 6]);
set.retain(|&k| k % 2 == 0);
assert_eq!(set.len(), 3);

To demonstrate that exactly only the false elements are filtered out we could potentially change the example so that it fits better with the alternate definition:

let mut set = HashSet::from([1, 2, 3, 4, 5, 6, 7]);
set.retain(|&k| k % 2 == 0);
assert_eq!(set.len(), 3);
@aalekhpatel07 aalekhpatel07 added the A-docs Area: Documentation for any part of the project, including the compiler, standard library, and tools label Jan 6, 2023
@compiler-errors
Copy link
Member

Alternatively, since HashSet implements PartialEq, this is even more clear:

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::from([1, 2, 3, 4, 5, 6]);
    set.retain(|&k| k % 2 == 0);
    assert_eq!(set, HashSet::from([2, 4, 6]));
}

@Ezrashaw
Copy link
Contributor

Ezrashaw commented Jan 7, 2023

@rustbot claim

matthiaskrgr added a commit to matthiaskrgr/rust that referenced this issue Jan 7, 2023
…hnTitor

docs: make `HashSet::retain` doctest more clear

Fixes rust-lang#106535

Extremely simple fix suggested by `@compiler-errors` in the linked issue.
@bors bors closed this as completed in ee1992c Jan 8, 2023
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
A-docs Area: Documentation for any part of the project, including the compiler, standard library, and tools
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants