Rust 闭包可变借用参数生命周期如何处理? - V2EX
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
bianweiall
V2EX    Rust

Rust 闭包可变借用参数生命周期如何处理?

  •  
  •   bianweiall 2022-11-09 17:11:42 +08:00 2021 次点击
    这是一个创建于 1097 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想在闭包参数里传可变借用,需要如何解决生命周期问题?

    rustc 1.65.0

    296 | do_demo(|demo| async move { | ______________-----_^ | | | | | | | return type of closure `impl Future<Output = String>` contains a lifetime `'2` | | has type `&'1 mut Demo` 297 | | println!("demo: {:?}", demo); 298 | | demo.print_mut(); 299 | | format!("test demo, id: {}", demo.id) 300 | | }) | |_____^ returning this value requires that `'1` must outlive `'2` 
    use std::future::Future; #[derive(Debug)] struct Demo { id: i32, name: String, } impl Demo { fn print(self) { println!("id:{}, name:{:?}", self.id, self.name); } fn print_mut(&mut self) { println!("id:{}, name:{:?}", self.id, self.name); } } async fn do_demo<F, U>(mut f: F) -> Result<(), String> where F: for<'a> FnMut(&'a Demo) -> U, U: Future<Output = String>, { let demo = Demo { id: 1, name: "test".to_string(), }; let ret = f(&demo).await; demo.print(); println!("f() ret: {:?}", ret); Ok(()) } #[tokio::test] async fn demo() { do_demo(|demo| async move { println!("demo: {:?}", demo); demo.print_mut(); format!("test demo, id: {}", demo.id) }) .await .unwrap(); } 
    3 条回复    2022-11-18 23:03:54 +08:00
    ihciah
        1
    ihciah  
       2022-11-09 19:01:35 +08:00
    因为生成的 Future 捕获了 &Demo ,所以要求 &Demo 生命周期长于 Future 。
    但 async 闭包返回值的类型写不出来,所以不好约束。一个办法是手动定义带生命周期标记的结构并实现 Future ,但明显实际用起来不太好使。
    不知道有没有其他 hack 的办法,我想到一个办法是自定义一个类似 Fn/FnMut 这种的 Trait ,然后在关联类型上标生命周期,这样 fn 定义上就可以把 &Demo 的生命周期和 Future 关联起来了。

    ```
    #![feature(type_alias_impl_trait)]

    use std::future::Future;

    #[derive(Debug)]
    struct Demo {
    id: i32,
    name: String,
    }

    impl Demo {
    fn print(self) {
    println!("id:{}, name:{:?}", self.id, self.name);
    }
    fn print_ref(&self) {
    println!("id:{}, name:{:?}", self.id, self.name);
    }
    }

    trait MyFn {
    type Future<'a>: Future<Output = String>;
    fn call<'a>(&self, param: &'a Demo) -> Self::Future<'a>;
    }

    struct DemoFn;
    impl MyFn for DemoFn {
    type Future<'a> = impl Future<Output = String> + 'a;

    fn call<'a>(&self, param: &'a Demo) -> Self::Future<'a> {
    async move {
    println!("demo: {:?}", param);
    param.print_ref();
    format!("test demo, id: {}", param.id)
    }
    }
    }

    async fn do_demo<F>(f: F) -> Result<(), String>
    where
    F: MyFn,
    {
    let demo = Demo {
    id: 1,
    name: "test".to_string(),
    };

    let ret = f.call(&demo).await;

    // demo.print();

    println!("f() ret: {:?}", ret);

    Ok(())
    }

    async fn demo() {
    do_demo(DemoFn)
    .await
    .unwrap();
    }
    ```
    liuxu
        2
    liuxu  
       2022-11-10 13:55:34 +08:00
    异步或者多线程,所有权还是应该交出去,借用把事情搞复杂了,四不像了

    use std::future::Future;

    #[derive(Debug, Clone)]
    struct Demo {
    id: i32,
    name: String,
    }

    impl Demo {
    #[allow(dead_code)]
    fn print(&self) {
    println!("id:{}, name:{:?}", self.id, self.name);
    }
    fn print_mut(&mut self) {
    println!("id:{}, name:{:?}", self.id, self.name);
    }
    }

    async fn do_demo<F, U>(f: F) -> Result<(), String>
    where
    F: for<'a> FnOnce(Demo) -> U,
    U: Future<Output = String>,
    {
    let demo = Demo {
    id: 1,
    name: "test".to_string(),
    };

    let ret = f(demo.clone()).await;

    demo.print();

    println!("f() ret: {:?}", ret);

    Ok(())
    }

    #[tokio::main]
    async fn main() {
    do_demo(|mut demo| async move {
    println!("demo: {:?}", demo);
    demo.print_mut();
    format!("test demo, id: {}", demo.id)
    })
    .await
    .unwrap();
    }
    chinawrj
        3
    chinawrj  
       2022-11-18 23:03:54 +08:00 via Android
    @liuxu 正解。。
    关于     帮助文档     自助推广系统     博客     API     FAQ     Solana     5269 人在线   最高记录 6679       Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 23ms UTC 08:35 PVG 16:35 LAX 00:35 JFK 03:35
    Do have faith in what you're doing.
    ubao msn snddm index pchome yahoo rakuten mypaper meadowduck bidyahoo youbao zxmzxm asda bnvcg cvbfg dfscv mmhjk xxddc yybgb zznbn ccubao uaitu acv GXCV ET GDG YH FG BCVB FJFH CBRE CBC GDG ET54 WRWR RWER WREW WRWER RWER SDG EW SF DSFSF fbbs ubao fhd dfg ewr dg df ewwr ewwr et ruyut utut dfg fgd gdfgt etg dfgt dfgd ert4 gd fgg wr 235 wer3 we vsdf sdf gdf ert xcv sdf rwer hfd dfg cvb rwf afb dfh jgh bmn lgh rty gfds cxv xcv xcs vdas fdf fgd cv sdf tert sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf sdf shasha9178 shasha9178 shasha9178 shasha9178 shasha9178 liflif2 liflif2 liflif2 liflif2 liflif2 liblib3 liblib3 liblib3 liblib3 liblib3 zhazha444 zhazha444 zhazha444 zhazha444 zhazha444 dende5 dende denden denden2 denden21 fenfen9 fenf619 fen619 fenfe9 fe619 sdf sdf sdf sdf sdf zhazh90 zhazh0 zhaa50 zha90 zh590 zho zhoz zhozh zhozho zhozho2 lislis lls95 lili95 lils5 liss9 sdf0ty987 sdft876 sdft9876 sdf09876 sd0t9876 sdf0ty98 sdf0976 sdf0ty986 sdf0ty96 sdf0t76 sdf0876 df0ty98 sf0t876 sd0ty76 sdy76 sdf76 sdf0t76 sdf0ty9 sdf0ty98 sdf0ty987 sdf0ty98 sdf6676 sdf876 sd876 sd876 sdf6 sdf6 sdf9876 sdf0t sdf06 sdf0ty9776 sdf0ty9776 sdf0ty76 sdf8876 sdf0t sd6 sdf06 s688876 sd688 sdf86