我正在尝试从具有嵌套矢量的数据中收集数据到Result<Vec_>>
中。考虑以下code:
type Result<T> = std::result::Result<T, String>;
fn f(x: u32) -> Result<Vec<u32>> {
Ok(vec![x, x, x])
}
fn main() {
let sources = [1, 2, 3];
let out1: Vec<Result<Vec<u32>>> = sources.iter().map(|x| f(*x)).collect();
let out2: Result<Vec<Vec<u32>>> = sources.iter().map(|x| f(*x)).collect();
// let out3: Result<Vec<u32>> = sources.iter().map(|x| f(*x)).collect();
}
out1
和out2
都可以正确编译,但是我真正想得到的是out2
的一种变体,其中两个嵌套向量被展平为一个。如果尝试使用out3
,则会出现以下错误:
error[E0277]: a collection of type `std::vec::Vec<u32>` cannot be built from an iterator over elements of type `std::vec::Vec<u32>`
--> src/main.rs:11:64
|
11 | let out3: Result<Vec<u32>> = sources.iter().map(|x| f(*x)).collect();
| ^^^^^^^ a collection of type `std::vec::Vec<u32>` cannot be built from `std::iter::Iterator<Item=std::vec::Vec<u32>>`
|
= help: the trait `std::iter::FromIterator<std::vec::Vec<u32>>` is not implemented for `std::vec::Vec<u32>`
= note: required because of the requirements on the impl of `std::iter::FromIterator<std::result::Result<std::vec::Vec<u32>, std::string::String>>` for `std::result::Result<std::vec::Vec<u32>, std::string::String>`
如何在不构建中间结构的情况下进入平坦的Result<Vec<_>>
?