Is there a nicer way to get a value from a HashSet of length 1?

I'm currently using this in a filter_map, but it feels a bit dirty.

(clause.literals.len() == 1).then(|| *clause.literals.iter().next().unwrap())

I'm mostly talking about the right side where I have to use an iterator.

If you can live with multi-element maps still returning an (arbitrary) item, then this is just .iter().copied().next() or .into_iter().next().

If you don't want to return any element from multi-item maps, then you can match on two consecutive items:

let mut iter = (…).into_iter();
match (, {
    (item @ Some(_), None) => item,
    _ => None,

The itertools crate has exactly_one() as well as at_most_one().


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.