I have a toy app where I can add entries to a collection, but I cannot modify the add
method to keep track of the smallest entry.
The basic version is here
I think I need to add something like a smallest_entry: Option<&'a Entry>
to the struct
that holds the entries, but I cannot figure out how to modify the add_entry
the data structure is
struct Entry {
pub value: usize,
}
struct Source {
pub entries: Vec<Entry>,
// pub smallest_entry: Option<&'a Entry>,
}
struct SourcesRepository {
pub map: HashMap<String, Source>,
}
and the current add_entry
method is
impl SourcesRepository {
fn add_entry(&mut self, title: String, entry: Entry) {
match self.map.get_mut(&title) {
Some(source) => {
// we already have a Source for this title: add new entry to it
source.entries.push(entry);
}
None => {
// no source existing for this title: create new and add entry
let mut source = Source {
entries: Vec::new(),
};
source.entries.push(entry);
self.map.insert(title, source);
}
}
}
}
I imagine once I have the source
entry I should compare it with the smallest_entry
and update that reference if the new entry is smaller. I've tried to modify the code but I cannot make the lifetimes work.
impl SourcesRepository<'_> {
fn add_entry(&mut self, title: String, entry: Entry) {
match self.map.get_mut(&title) {
Some(source) => {
// we already have a Source for this title: add new entry to it
match source.smallest_entry {
Some(smallest_entry) => {
if entry.value < smallest_entry.value {
source.smallest_entry = Some(&entry);
}
}
None => {
source.smallest_entry = Some(&entry);
}
}
source.entries.push(entry);
}
None => {
// no source existing for this title: create new and add entry
let mut source = Source {
entries: Vec::new(),
smallest_entry: Some(&entry),
};
source.entries.push(entry);
self.map.insert(title, source);
}
}
}
}