rust 无法指定返回rusqlite::MappedList的返回类型

t98cgbkg  于 2023-10-20  发布在  SQLite
关注(0)|答案(1)|浏览(111)

我想写一个Rust函数,提供一个rusqlite::Statement和一个时间间隔(from,to),返回一个rusqlite::MappedRows,然后我可以用它作为一个interator从数据库中读取行。
get_mapped_rows函数应该返回MappedRows结构:

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,结果的FnMutFromSql部分。但没找到。我觉得这不是解决我问题的正确方法。

**更新:**这是它工作的原因:

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)?)
        })
}
lg40wkob

lg40wkob1#

我通过将get_mapped_rows函数更新为以下内容来使其工作:

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)?)
        })
}

我在这里学到的是,你使用impl FnMut来表示编译器已知的类型(或者更确切地说,我猜是签名)。我最初尝试在Result中使用impl FromSql而不是i64,但编译器不喜欢这样。

相关问题