Created
March 18, 2020 19:30
-
-
Save NebulaFox/7181c8da0ccfe94ad2f4132bf2382a8f to your computer and use it in GitHub Desktop.
Unify HashSet contains and Vec contains solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[allow(dead_code)] | |
fn contains<'a, V, T, Q>(arr: V, value: &Q) -> bool | |
where | |
T: 'a + std::cmp::PartialEq<Q>, | |
V: std::iter::IntoIterator<Item = &'a T> | |
{ | |
arr.into_iter().any(|v| v == value) | |
} | |
#[test] | |
fn test_contains_hash_set() { | |
use std::collections::HashSet; | |
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); | |
assert!(contains(&hs_str, &value_string)); | |
assert!(contains(&hs_string, &value_str)); | |
assert!(contains(&hs_string, &"a")); | |
} | |
#[test] | |
fn test_contains_vec() { | |
let array_str = ["a", "b", "c"]; | |
let array_string = ["a".to_string(), "b".to_string(), "c".to_string()]; | |
let value_str = "b"; | |
let value_string = String::from(value_str); | |
assert!(contains(&array_str, &value_string)); | |
assert!(contains(&array_string, &value_str)); | |
assert!(contains(&array_string, &"b")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment