re: Daily Coding Puzzles - Nov 4th - Nov 9th VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Wednesday Array.diff (6 KYU): Your goal in this kata is to implement a difference function, which subtracts one list from another and returns th...
 

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()
}
code of conduct - report abuse