首页 > 解决方案 > 引用如何逃脱闭包?`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

标签: rust

解决方案


推荐阅读