rust 装箱一个rusqlite迭代器

zpf6vheq  于 5个月前  发布在  SQLite
关注(0)|答案(1)|浏览(58)

bounty将在3天后过期。回答此问题可获得+500声望奖励。Matt Joiner希望引起更多关注此问题。

在使用preparequery时,我很难弄清楚如何返回迭代器(implBox)。
以下是我尝试过的:

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

字符串
问题是prepared语句是函数作用域(error[E0515]: cannot return value referencing temporary value)拥有的临时变量。

du7egjpx

du7egjpx1#

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

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>>,
}

字符串
Github来源:
它的FallibleStreamingIterator实现看起来像

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

    #[inline]
    fn advance(&mut self) -> Result<()> {
    ...


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`)


可能的解决办法是
1.返回拥有的rusqlite::Statement<'a>并查询所需位置
1.或返回计算的结果集(拥有的)

相关问题