expression

rusqlite: map query rows into Rust structs

Map each row into a typed Rust value. Row conversion can fail, so collect the iterator as a Result rather than ignoring individual row errors. ORDER BY makes the output order explicit. Run in the accompanying Cargo project. Expected stdout (not executed): 1: Pen 2: Book Common mistake: Silently discarding conversion errors with filter_map(Result::ok).

Formal Syntax & Structure

rust syntaxrust
stmt.query_map(params, |row| ...)?

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    #[derive(Debug)]    struct Item { id: i64, name: String }    let db = rusqlite::Connection::open_in_memory()?;    db.execute_batch("CREATE TABLE item (id INTEGER PRIMARY KEY, name TEXT); INSERT INTO item VALUES (2, 'Book'), (1, 'Pen');")?;    let mut stmt = db.prepare("SELECT id, name FROM item ORDER BY id")?;    let rows = stmt.query_map([], |r| Ok(Item { id: r.get(0)?, name: r.get(1)? }))?;    let items = rows.collect::<rusqlite::Result<Vec<_>>>()?;    for item in items { println!("{}: {}", item.id, item.name); }    Ok(())}
Rust Reference