为什么闭包的连接参数需要“静态绑定”?

Why does the connection param of the closure need to be 'static bound?

提问人:Hsu Jason 提问时间:6/15/2023 最后编辑:Chayim FriedmanHsu Jason 更新时间:6/15/2023 访问量:55

问:

以下代码无效

pub async fn async_execute_in_transcation<T: AsyncConnection<Backend = Pg>>(
    connection: &mut T,
) -> Result<(), Error> {
    connection.transaction::<(), diesel::result::Error, _>(|conn| async {
        diesel::sql_query("insert into posts (title, body) values ('async_execute_in_transcation', 'async_execute_in_transcation body')")
        .execute(conn).await?;
        Ok(())
      }.scope_boxed()
   ).await?;
    Ok(())
}
error[E0310]: the parameter type `T` may not live long enough
  --> src/main.rs:15:67
   |
15 |       connection.transaction::<(), diesel::result::Error, _>(|conn| async {
   |  ___________________________________________________________________^
16 | |         diesel::sql_query("insert into posts (title, body) values ('async_execute_in_transcation', 'async_execute_in_transcation body')")
17 | |         .execute(conn).await?;
18 | |         Ok(())
19 | |       }.scope_boxed()
   | |_____________________^ ...so that the type `T` will meet its required lifetime bounds
   |
help: consider adding an explicit lifetime bound...
   |
12 | pub async fn async_execute_in_transcation<T: AsyncConnection<Backend = Pg> + 'static>(
   |                                                                            +++++++++

我需要将“静态绑定”添加到 T 泛型或添加“静态生存期注释”connection: &'static mut T“以使其编译。为什么?

防锈 瓶盖 lifetime Rust-Diesel

评论


答: 暂无答案