Idiomatic way to check if intersection of 2 sets is empty

foo and bar are both BTreeSet<T>. I want a way to check if intersection between them are empty. I don't care about the exact content. Currently, I do this:

let is_empty = !foo.iter().any(|x| bar.contains(x));

Is there a better way?

let is_empty = foo.is_disjoint(&bar);

https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.is_disjoint

Edit: I missed the BTreeSet::is_disjoint() method. It's clearly better than .intersection() for your use case.

1 Like

Don't beat yourself up -- if you click the src link, you'll see that is_disjoint is implemented exactly like what you first wrote. But yes, the simple method name is better to show intent.

1 Like

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.