gpt4 book ai didi

rust - 我怎样才能延长结构的生命周期,以便我可以用它调用 tokio::run?

转载 作者:行者123 更新时间:2023-11-29 07:58:00 25 4
gpt4 key购买 nike

我有一个有效的函数:

extern crate tokio;

use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Interval;

fn run(label: String) -> impl Future<Item = (), Error = ()> {
Interval::new(Instant::now(), Duration::from_millis(1000))
.for_each(move |instant| {
println!("fire; instant={:?}, label={:?}", instant, label);
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e))
}

fn main() {
tokio::run(run("Hello".to_string()));
}

playground

在这种情况下,我想创建一个包含一些参数(label)的结构,方法 run 将利用这些参数:

extern crate tokio;

use std::time::{Duration, Instant};
use tokio::prelude::*;
use tokio::timer::Interval;

struct Ir {
label: String,
}

impl Ir {
fn new(label: String) -> Ir {
Ir { label }
}

fn run(&self) -> impl Future<Item = (), Error = ()> + '_ {
Interval::new(Instant::now(), Duration::from_millis(1000))
.for_each(move |instant| {
println!("fire; instant={:?}, label={:?}", instant, self.label);
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e))
}
}

fn main() {
let ir = Ir::new("Hello".to_string());
tokio::run(ir.run());
}

playground

我得到的是:

error[E0597]: `ir` does not live long enough
--> src/main.rs:28:16
|
28 | tokio::run(ir.run());
| ^^ borrowed value does not live long enough
29 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...

我已经阅读了“Rust by Example”中的“Advanced Lifetimes”和“Validating References with Lifetimes”,但我仍然不明白如何修复它。
为什么 ir 活得不够长?
我在尝试调用 ir.run() 的同一范围内创建了它,因此我认为它会一直存在。

最佳答案

如果你重写:

tokio::run(ir.run());

作为:

tokio::run(Ir::run(&ir))

错误变得更清楚了:

error[E0597]: `ir` does not live long enough
--> src/main.rs:28:24
|
28 | tokio::run(Ir::run(&ir));
| ^^ borrowed value does not live long enough
29 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...

tokio::run Future 需要一个'static 生命周期:

pub fn run<F>(future: F) 
where
F: Future<Item = (), Error = ()> + Send + 'static,

为避免生命周期问题,请考虑使用 Ir 值:

fn run(self) -> impl Future<Item = (), Error = ()>  {
Interval::new(Instant::now(), Duration::from_millis(1000))
.for_each(move |instant| {
println!("fire; instant={:?}, label={:?}", instant, self.label);
Ok(())
})
.map_err(|e| panic!("interval errored; err={:?}", e))
}

关于rust - 我怎样才能延长结构的生命周期,以便我可以用它调用 tokio::run?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53062958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com