Rusqlite Insert & Rust Match - problem assigning Err to Result enum
⚓ Rust 📅 2026-02-27 👤 surdeus 👁️ 1Have written a function to insert a vector of records into an SQLite database. I employ the match statement to test if each insert worked. If there is an error I have an Err option. In it I thought I could print a message, assign Err(e) to the data_inserted variable, then break to exit the a loop and return to main with the error contained in the returned Result via the "return data_inserted" line. But I get an error on Err(e) that says type annotation needed, cannot infer type of type parameter T declared on the enum Result. Consider specifying the generic arguments ::,T, rusqlite::Error>.
I do not understand how to apply the error message so I commented out the two lines and inserted return Err(e) and that compiles. So two questions. 1) Why don't the commented out two lines work? 2) With "return Err(e)" in place, if there is an error, I think the for loop and function end but in the process is the error assigned to the data_inserted variable and is that Result enum what's returned to main or is something else happening?
Below is the function.
use crate::structures::structures::Record;
use rusqlite::{Connection, Result, named_params};
pub fn insert_records(conn: &Connection, records: &mut Vec<Record>) -> Result<(), rusqlite::Error> {
let mut data_inserted: Result<(), rusqlite::Error> = Ok(());
for record in records {
data_inserted = match conn.execute(
"INSERT INTO data (date, open, high, low, close, volume)
VALUES (:date, :open, :high, :low, :close, :volume)",
named_params! {
":date": &record.date,
":open": &record.open,
":high": &record.high,
":low": &record.low,
":close": &record.close,
":volume": &record.volume,
},
){
rusqlite::Result::Ok(_) => {
eprintln!("Record added successfully");
Ok(())
}
rusqlite::Result::Err(e) => {
eprintln!("Error adding record: {}", e);
return Err(e);
// Err(e);
// break
}
};
} // end for loop
return data_inserted
}
3 posts - 2 participants
🏷️ Rust_feed