Skip to content

Instantly share code, notes, and snippets.

@anthonynsimon
Created Aug 9, 2018
Embed
What would you like to do?
rust two ways
use std::collections::HashMap;
#[derive(Hash, Eq, PartialEq, Debug)]
struct Item {
rank: u32,
revision: u32,
}
fn should_insert(item: &Item, acc: &HashMap<u32, Item>) -> bool {
match acc.get(&item.rank) {
Some(existing) if existing.revision < item.revision => true,
None => true,
_ => false,
}
}
fn main() {
let data = vec![
Item { rank: 1, revision: 1 },
Item { rank: 0, revision: 1 },
Item { rank: 4, revision: 1 },
Item { rank: 1, revision: 2 },
Item { rank: 0, revision: 2 },
Item { rank: 3, revision: 1 },
];
let mut result: HashMap<u32, Item> = HashMap::new();
for item in data {
if should_insert(&item, &result) {
result.insert(item.rank, item);
}
}
println!("{:?}", result);
}
use std::collections::HashMap;
#[derive(Hash, Eq, PartialEq, Debug)]
struct Item {
rank: u32,
revision: u32,
}
fn main() {
let data = vec![
Item { rank: 1, revision: 1 },
Item { rank: 0, revision: 1 },
Item { rank: 4, revision: 1 },
Item { rank: 1, revision: 2 },
Item { rank: 0, revision: 2 },
Item { rank: 3, revision: 1 },
];
let mut result: HashMap<u32, Item> = HashMap::new();
for item in data {
// Decide if item should be kept or discarded
let to_insert = match result.get(&item.rank) {
// Mark item for insert if key exists and revision is greater than existing
Some(existing) if existing.revision < item.revision => Some(item),
// or if key doesn't exist yet
None => Some(item),
// otherwise discard
_ => None,
};
// Insert item if marked
if let Some(new_item) = to_insert {
result.insert(new_item.rank, new_item);
}
}
println!("{:?}", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment