我刚接触Rust,想要将一些代码变成异步的,以便并行运行多个任务。以下是一个简化的示例:
use futures::future::join_all;
#[tokio::main]
async fn main() {
let mut list = Vec::new();
for i in 1..10 {
let my_str = format!("Value is: {:?}", &i);
let future = do_something(&my_str);
list.push(future);
}
join_all(list).await;
}
async fn do_something(value: &str)
{
println!("value is: {:?}", value);
}
当调用do_something(&my_str)时,会出现“借用的值未能生存到足够长的时间”错误。通过将do_something更改为接受String而不是&str,我可以使代码编译。然而,要求使用String似乎有点奇怪,因为&str也可以工作。这里是否有更好的模式可用?谢谢!