Improving code is a crucial part of software development. Not only does it make code more readable for future developers, but it also helps to make it shorter and faster.
One way to improve code is by making it shorter. This can be achieved through the use of functions or loops, which can help to simplify complex sections of code. Additionally, removing unnecessary code can also help to make code shorter and more efficient.
For example we have two vectors and we want to remove duplicates from both of them
fn main() {
let vector_1 = vec!['l', 'o', 'w'];
let vector_2 = vec!['w', 'v', 'e'];
let vec_1 = remove_elements(&vector_1, &vector_2);
let vec_2 = remove_elements(&vector_2, &vector_1);
println!("vec_1 {:?}", vec_1);
println!("vec_2 {:?}", vec_2);
}
Here's where I started
fn remove_duplicates(edit: &Vec<char>, compare: &Vec<char>) -> Vec<char> {
let mut result = Vec::new();
let mut set = std::collections::HashSet::new();
for id in compare {
set.insert(id);
}
for id in edit {
if !set.contains(id) {
result.push(*id);
}
}
result
}
And this is how I write now
fn remove_duplicates(edit: &Vec<char>, compare: &Vec<char>) -> Vec<char> {
let mut temp_vec: Vec<char> = edit.clone();
temp_vec.retain(|e| !compare.contains(e));
temp_vec.clone()
}
See also “Automating button creation”
Top comments (0)