How can I Update and remove Vector values based on a condition in Rust

I there I'm a newbie. Just need little help. :slight_smile:

This is my vector: will help you to understand my problem better.

let mut entries = vec![("Batman",1000),

One superhero's name and the other is the money he/she added to an account.

1)I want to get Batman entries

2)Let say I want to minus 2500 from Batman's account. So the latest entry of ("Batman",2000) will be removed, and the remaining 500 would be removed from his other entry.

3)if money equals zero remove that entry.

Final Result:

let mut entries = vec![("Batman",500),

What would be the most efficient method to resolve that.
Any help would be appreciated.

Have you considered using a HashMap instead of a Vec? It supports this kind of lookup natively.

1 Like

Actually, I have reduced the number of parameters from 3 to 2 in this example.

You can probably still use a map.

The deleted retain suggestion seemed fine to me... but a map does make more sense from what you've shared about the use case. Especially since you asked about efficiency.

Here's an example for both. Given the inputs I assumed the order of the outputs for the Vec approach don't matter. But there may be more requirements to the use case you haven't made us aware of.

Yeah, I deleted since I misunderstood the requirements, so retain could work in someway, but it is not enough by itself.

I think you should reconsider the data model here. If each entry represents a transaction, then you don't withdraw money from an account by deleting old transactions: you create a new transaction with a negative amount ("Batman", -2500) and just add it to the list of transactions. But if each entry represents a whole account, there should not be two entries for "Batman" and each transaction should simply update the balance.

If you are doing something that doesn't fit either of those two solutions, please elaborate on the problem you are trying to solve. There is probably a more appropriate data structure for whatever it is.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.