Iterator + Mapped Rows: Can I better use an iterator to determine / assign values
⚓ Rust 📅 2026-05-01 👤 surdeus 👁️ 3I have a function that returns a vector of structures containing data from an sql database query via rusqlite. It works. Can I fold the "let maxvalue", "let minvalue" and "for loop" functionality into the "let mut closing_values" step by applying additional methods in some way? Or is there simply a better way to go about do this? Any assistance will be appreciated.
pub fn get_closing_values(start_date: &str) -> Result<Vec<ClosingByDate>, CustomError> {
let db_file_path = "stock_data.db";
let conn = Connection::open(db_file_path)?;
let mut stmt = conn.prepare(
"Select date, fdate, close
From data
Where date >= (:startdate)
Order By date Asc"
)?;
let row_iter = stmt.query_map(&[(":startdate", &start_date)], |row|
{
Ok(ClosingByDate {
date: row.get(0)?,
fdate: row.get(1)?,
close: row.get(2)?,
min: false,
max: false,
})
})?;
let mut closing_values: Vec<ClosingByDate> = row_iter
.filter_map(|item| item.ok())
.collect();
let maxvalue: f64 = closing_values.iter().max_by(|a, b| a.close.total_cmp(&b.close)).unwrap().close;
let minvalue: f64 = closing_values.iter().min_by(|a, b| a.close.total_cmp(&b.close)).unwrap().close;
for element in &mut closing_values {
if element.close == maxvalue {
element.max = true;
} else if element.close == minvalue {
element.min = true;
}
}
Ok(closing_values)
}
3 posts - 3 participants
🏷️ Rust_feed