pub fn uniq<T>(collection: &[T]) -> Vec<T>Expand description
Remove duplicate elements from a collection, preserving the order of their first occurrence.
This function takes a slice of items and returns a new Vec<T> containing only the unique elements,
preserving the order in which they first appear in the input collection.
Note: Unlike the previous implementation, this version does not require T to implement Hash and Eq.
This allows the function to work with types like floating-point numbers (f32, f64), which do not implement Eq
due to the presence of NaN (Not a Number) values.
However, this approach has a time complexity of O(n²) because it performs a linear search for each element to check for duplicates. Use it with caution on large collections.
§Arguments
collection- A slice of items from which to extract unique elements.
§Type Parameters
T- The type of elements in the collection. Must implementPartialEqandClone.
§Returns
Vec<T>- A vector containing the unique elements from the input collection, in the order they first appear.
§Examples
use lowdash::uniq;
let numbers = vec![1, 2, 2, 3, 4, 3, 5];
let unique_numbers = uniq(&numbers);
assert_eq!(unique_numbers, vec![1, 2, 3, 4, 5]);use lowdash::uniq;
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
age: u32,
}
let people = vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Carol".to_string(), age: 35 },
];
let unique_people = uniq(&people);
assert_eq!(unique_people, vec![
Person { name: "Alice".to_string(), age: 25 },
Person { name: "Bob".to_string(), age: 30 },
Person { name: "Carol".to_string(), age: 35 },
]);