I have a vector of Cat objects. Now I want to delete a cat with a specific name from the vector. I will be using the retain function for that.
But I also want to check if the retain function has deleted an object or not. How do I do that? It doesn't return anything.
One possible solution would be taking the difference of the size of the vector before and after the deletion of the object, but maybe there is a more clean solution?
Demo code:
//Struct Cat
pub struct Cat {
pub name: String,
age: u8,
//color: CatColor,
//race: CatRace,
}
fn main() {
//Making vector to hold cats
let mut cats = std::vec::Vec::<Cat>::new();
//Initializing two Cat-objects
let c1 = Cat {
name: "Tom".to_string(),
age: 16,
};
let c2 = Cat {
name: "Mr. Miauw".to_string(),
age: 6,
};
//Adding cats to vector
cats.push(c1);
cats.push(c2);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Here I want to delete the cats and check
//if a cat was succesfully deleted!!!! HOW??
//One of the following two options would be nice
//let succes : bool = cats.retain(|cat| &cat.name == "Tom");
//let amountDeleted : u32 = cats.retain(|cat| &cat.name == "Tom");
cats.retain(|cat| &cat.name == "Tom");
}
Not op but I have some misunderstandings.
I slightly changed your playground example, adding 2 more cats and removing only one. amountDeleted is getting tracked, okay, but cats we have only one. From total 4 cats, removing only one, and we're having only one cat.
retain retains everything that passes the predicate; removing all but one Cat is correct. The predicate, however, counts deleted entries wrong; it's adding one whenever an entry is not deleted, which is the opposite of what it should do. Changing the check to if !b fixes this.
I think actually the cleanest solution is checking if the length of the vector changed. That's 1. explicitly mirroring the semantics of what you are trying to do, and 2. it does not require mutating additional state in the predicate function.