rust - 引用如何逃脱闭包?`packet` 在这里逃脱了闭包体
问题描述
在下面的例子中,我不明白为什么它抱怨packet
逃避闭包。是packet
的,它的生命周期很短,它的生命周期只有on_packet
函数调用持续的时间。但是,当我调用时on_packet_render(&packet)
,我并没有移动packet
,我只是传递了一个引用,它将被使用并且on_packet_render
当我在里面时调用将返回on_packet
,所以我不明白为什么会出现这个错误。
use std::sync::Arc;
pub type DecoderProvider = Arc<dyn Fn(&dyn Fn(&Option<&Arc<u8>>))>;
trait DecodedPacket<'a, T> {}
fn main() {
let mut on_packet_render = |packet: &Option<Box<dyn DecodedPacket<u8>>>| {
if let Some(packet) = packet {
}
};
let mut on_packet: Arc<
dyn for<'c, 'd> FnMut(
Option<Box<dyn DecodedPacket<'c, u8> + 'd>>,
)> = Arc::new(|packet| {
on_packet_render(&packet);
});
}
错误:
error[E0521]: borrowed data escapes outside of closure
--> src/main.rs:15:9
|
6 | let mut on_packet_render = |packet: &Option<Box<dyn DecodedPacket<u8>>>| {
| -------------------- `on_packet_render` declared here, outside of the closure body
...
14 | )> = Arc::new(|packet| {
| ------ `packet` is a reference that is only valid in the closure body
15 | on_packet_render(&packet);
| ^^^^^^^^^^^^^^^^^^^^^^^^^ `packet` escapes the closure body here
解决方案
推荐阅读
- javascript - 制表符,有没有办法在页脚中添加页面总和?
- ios - 我在 Tableview 单元格中有collectionView。它总是返回零。我该如何解决?
- python - 合并Dataframe中不同列的纬度和经度,然后使用haversine作为距离
- sql-server - 在其他数据库上找不到记录时更新行值
- python - 在 Anaconda Navigator 中不显示 Pip 安装的软件包
- java - 在 JavaFX 2020 中嵌入 JOGL 或 LibGDX
- c - 为什么这个 c 程序要像这样转换成汇编程序?
- android - 未解决的参考:RecyclerView 尝试继承 Adapter
- c - openmp 并行程序比串行程序慢得多
- c# - 在 OWIN 自托管中使用集成的 Windows 身份验证发送大型 POST 请求