Dra*_*oon 2 chunks ownership rust
我试图一次对多个字符串块执行并行操作,并且发现借用检查器存在问题:
(对于上下文,identifiers是Vec<String>来自 CSV 文件的,client是 reqwest,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;
}
Run Code Online (Sandbox Code Playgroud)
给定块产生一个 Vec<&[String]> ,编译器抱怨它的identifiers寿命不够长,因为在引用切片时它可能会超出范围。实际上这不会发生,因为有等待。有没有一种方法可以告诉编译器这是安全的,或者是否有另一种方法可以为每个线程获取作为一组拥有的字符串的块?
有一个类似的问题,使用 into_owned() 作为解决方案,但是当我尝试这样做时,rustc 抱怨在 request_user 函数的编译时不知道切片大小。
编辑:还有其他一些问题:
有没有更直接的方法在每个线程中使用target而不需要Arc?从创建的那一刻起,就不需要修改,只需读取。如果没有,是否有一种方法可以将其从 Arc 中拉出,不需要 .as_str() 方法?
如何处理 tokio::spawn() 块中的多种错误类型?在实际使用中,我将收到其中的 fast_xml::Error 和 reqwest::Error 。没有 tokio spawn 的并发性,它可以正常工作。
有没有一种方法可以告诉编译器这是安全的,或者是否有另一种方法可以为每个线程获取作为一组拥有的字符串的块?
您可以使用crate 将 a 分块Vec<T>到 a 中Vec<Vec<T>> ,而无需克隆itertools:
use itertools::Itertools;
fn main() {
let items = vec![
String::from("foo"),
String::from("bar"),
String::from("baz"),
];
let chunked_items: Vec<Vec<String>> = items
.into_iter()
.chunks(2)
.into_iter()
.map(|chunk| chunk.collect())
.collect();
for chunk in chunked_items {
println!("{:?}", chunk);
}
}
Run Code Online (Sandbox Code Playgroud)
use itertools::Itertools;
fn main() {
let items = vec![
String::from("foo"),
String::from("bar"),
String::from("baz"),
];
let chunked_items: Vec<Vec<String>> = items
.into_iter()
.chunks(2)
.into_iter()
.map(|chunk| chunk.collect())
.collect();
for chunk in chunked_items {
println!("{:?}", chunk);
}
}
Run Code Online (Sandbox Code Playgroud)
这是基于此处的答案。
| 归档时间: |
|
| 查看次数: |
3044 次 |
| 最近记录: |