Logo

Programming-Idioms

History of Idiom 218 > diff from v18 to v19

Edit summary for version 19 by programming-idioms.org:
[Rust] We want intersection, not union

Version 18

2020-07-15, 18:51:22

Version 19

2020-07-18, 23:31:27

Idiom #218 List intersection

Create list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.

Idiom #218 List intersection

Create list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.

Extra Keywords
intersect and conjunction
Extra Keywords
intersect and conjunction
Imports
use std::collections::HashSet;
Imports
use std::collections::HashSet;
Code
let mut c: HashSet<_> = a.collect();
unique.extend(b);
let c = unique.into_iter();
Code
let set_a: HashSet<_> = a.into_iter().collect();
let set_b: HashSet<_> = b.into_iter().collect();
let c = set_a.intersection(&set_b);
Comments bubble
This treats the three lists as impl Iterator<Item = T>
Doc URL
https://doc.rust-lang.org/std/collections/struct.HashSet.html
Doc URL
https://doc.rust-lang.org/std/collections/hash_set/struct.Intersection.html
Demo URL
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=762ffc4474ad8fc7de7e7e8cad8dde17