装箱 rusqlite Rows 迭代器

tcn*_*tcn 9 rust

我在使用and时无法弄清楚如何返回迭代器(implBox)。preparequery

这是我尝试过的:

fn foo<'a>(
    conn: &'a mut rusqlite::Connection
) -> Box<impl 'a + fallible_streaming_iterator::FallibleStreamingIterator<Item=rusqlite::Row<'a>>> {
    Box::new(
        conn
            .prepare("SELECT a, b FROM t")
            .unwrap()
            .query(rusqlite::NO_PARAMS)
            .unwrap()
    )
}
Run Code Online (Sandbox Code Playgroud)

问题是准备好的语句是函数范围拥有的临时变量。( error[E0515]: cannot return value referencing temporary value)。

Mr.*_*jun 2

无法FallibleStreamingIterator<Item=rusqlite::Row<'a>>foo函数返回实例。

Rust 借用检查器不允许这样做。

要理解其中的原因,我们需要了解rusqlite::Rows<'a>其结构。

/// An handle for the resulting rows of a query.
#[must_use = "Rows is lazy and will do nothing unless consumed"]
pub struct Rows<'stmt> {
    pub(crate) stmt: Option<&'stmt Statement<'stmt>>,
    row: Option<Row<'stmt>>,
}
Run Code Online (Sandbox Code Playgroud)

Github 来源:Rows

它的FallibleStreamingIterator实现看起来像

impl<'stmt> FallibleStreamingIterator for Rows<'stmt> {
    type Error = Error;
    type Item = Row<'stmt>;

    #[inline]
    fn advance(&mut self) -> Result<()> {
    ...
Run Code Online (Sandbox Code Playgroud)

Github 来源:FallibleStreamingIterator

Rows持有对 的引用Statement。让我们尝试在这里推断寿命'stmt

      Statement (scope limited to `foo` func)
          |
         Rows (refers Statement so valid scope `foo`)
          |
FallibleStreamingIterator (refers Rows so valid scope `foo`)
Run Code Online (Sandbox Code Playgroud)

可能的解决方案可能是

  1. 返回拥有的rusqlite::Statement<'a>并查询所需位置
  2. 或返回计算结果集(拥有)