Skip to content

Instantly share code, notes, and snippets.

@NebulaFox
Last active March 18, 2020 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NebulaFox/17e7be1dc4aad92f04c0c57dfe5f63e3 to your computer and use it in GitHub Desktop.
Save NebulaFox/17e7be1dc4aad92f04c0c57dfe5f63e3 to your computer and use it in GitHub Desktop.
HashSet contains solution
use std::collections::HashSet;
fn contains<T, Q>(arr: &HashSet<T>, value: &Q) -> bool
where
T: std::cmp::PartialEq<Q>,
{
arr.iter().any(|v| v == value)
}
fn main() {
let hs_str: HashSet<&str> = ["a", "b", "c"].iter().copied().collect();
let hs_string: HashSet<String> = vec!["a".to_string(), "b".to_string(), "c".to_string()]
.into_iter()
.collect();
let value_str = "b";
let value_string = String::from(value_str);
let result_str = contains(&hs_str, &value_string);
let result_string = contains(&hs_string, &value_str);
let result_literal = contains(&hs_string, &"a"); // need to a &
println!(
"result: {} {} {}",
result_str, result_string, result_literal
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment