You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust函数返回rusqlite::MappedRows时的类型错误及解决

Rust中返回rusqlite::MappedRows迭代器的问题解决

需求

编写一个Rust函数,接收rusqlite::Statement和时间区间(from、to),返回rusqlite::MappedRows作为迭代器读取数据库行。

初始实现代码

get_mapped_rows函数

fn get_mapped_rows<'stmt>(
    stmt: &'stmt Statement,
    from: u64,
    to: u64
)-> MappedRows<'stmt, FnMut(&Row<'_>) -> Result<FromSql, Error>> {
    stmt
        .query(params![from, to])
            .unwrap()
            .mapped(Box::new(|row| {
                Ok(Box::new(row.get(0)?) as Box<dyn FromSql>)
            }))
}

调用函数get_rows

fn get_rows(conn: &mut Connection) {
    let mut stmt =
        conn.prepare("SELECT dbl_time FROM log WHERE time >= ?1 AND time < ?2")
        .unwrap();

    let mapped_rows = get_mapped_rows(stmt, 2, 4);

    while let Some(row_result) = mapped_rows.next() {
        match row_result {
            Ok(dbl_time) => { println!("dbl_time: {}", dbl_time); },
            _ => panic!("What happened?!"),
        }
    }
}

编译错误信息

error[E0782]: trait objects must include the `dyn` keyword
  --> src/main.rs:48:23
   |
48 | )-> MappedRows<'stmt, FnMut(&Row<'_>) -> Result<FromSql, Error>> {
   |                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
help: add `dyn` keyword before this trait
   |
48 | )-> MappedRows<'stmt, dyn FnMut(&Row<'_>) -> Result<FromSql, Error>> {
   |                       +++

error[E0782]: trait objects must include the `dyn` keyword
  --> src/main.rs:48:49
   |
48 | )-> MappedRows<'stmt, FnMut(&Row<'_>) -> Result<FromSql, Error>> {
   |                                                 ^^^^^^^
   |
help: add `dyn` keyword before this trait
   |
48 | )-> MappedRows<'stmt, FnMut(&Row<'_>) -> Result<dyn FromSql, Error>> {
   |                                                 +++

最终解决代码

按照提示添加dyn关键字或用Box包装均无效,最终通过以下代码解决问题:

fn get_mapped_rows<'stmt>(
    stmt: &'stmt mut Statement,
    from: u64,
    to: u64
)-> MappedRows<'stmt, impl FnMut(&Row<'_>) -> Result<i64, Error>> {
    stmt
        .query(params![from, to])
        .unwrap()
        .mapped(|row| {
            Ok(row.get(0)?)
        })
}

内容的提问来源于stack exchange,提问作者Marcus Johansson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:23:35