我正在尝试一次对几块字符串执行并行操作,但我发现借用检查器存在问题:
(对于上下文,来自 CSV 文件,identifiers
是reqwest 并且是一次写入多次读取)Vec<String>
client
target
Arc<String>
use futures::{stream, StreamExt};
use std::sync::Arc;
async fn nop(
person_ids: &[String],
target: &str,
url: &str,
) -> String {
let noop = format!("{} {}", target, url);
let noop2 = person_ids.iter().for_each(|f| {f.as_str();});
"Some text".into()
}
#[tokio::main]
async fn main() {
let target = Arc::new(String::from("sometext"));
let url = "http://example.com";
let identifiers = vec!["foo".into(), "bar".into(), "baz".into(), "qux".into(), "quux".into(), "quuz".into(), "corge".into(), "grault".into(), "garply".into(), "waldo".into(), "fred".into(), "plugh".into(), "xyzzy".into()];
let id_sets: Vec<&[String]> = identifiers.chunks(2).collect();
let responses = stream::iter(id_sets)
.map(|person_ids| {
let target = target.clone();
tokio::spawn( async move {
let resptext = nop(person_ids, target.as_str(), url).await;
})
})
.buffer_unordered(2);
responses
.for_each(|b| async { })
.await;
}
给定块产生一个 Vec<&[String]>,编译器抱怨它的identifiers
寿命不够长,因为它可能会在引用切片时超出范围。实际上这不会发生,因为有一个等待。有没有办法告诉编译器这是安全的,或者是否有另一种方法可以将块作为每个线程的一组拥有的字符串?
有一个类似的问题使用 into_owned() 作为解决方案,但是当我尝试这样做时,rustc 抱怨在 request_user 函数中编译时不知道切片大小。
编辑:还有一些其他问题:
是否有更直接的方式
target
在每个线程中使用而不需要 Arc?从创建的那一刻起,它就不需要修改,只需读取即可。如果没有,有没有办法将它从不需要 .as_str() 方法的 Arc 中拉出来?您如何处理 tokio::spawn() 块中的多种错误类型?在实际使用中,我将在其中收到 quick_xml::Error 和 reqwest::Error 。它可以在没有 tokio spawn 的情况下正常工作。