想在闭包参数里传可变借用,需要如何解决生命周期问题?
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();
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.