DEV Community

Discussion on: Daily Coding Puzzles - Nov 4th - Nov 9th

Collapse
 
jay profile image
Jay

Rust

  • With Liftime. The returned Vec<&T> has elements borrowed and valid until the list1 is valid.
fn diff<'a, T>(list1: &'a [T], list2: &[T]) -> Vec<&'a T>
where
    T: PartialEq,
{
    list1.into_iter().filter(|e| !list2.contains(e)).collect()
}
  • Without lifetime We return a new Vec free from any list provided, by cloning the data. The generic data type only allows the data type that implements Clone trait to be passed.
fn diff2<T>(list1: &[T], list2: &[T]) -> Vec<T>
where
    T: PartialEq + Clone,
{
    list1
        .into_iter()
        .map(|x| x.clone())
        .filter(|e| !list2.contains(&e))
        .collect()
}