我试图.iter()
在与 结合使用时进行错误处理.flat_map
,其中包含一个.iter().map()
。
该场景正在获取Event
属于一组组织的所有 s,其中嵌套.iter().map()
用于获取每个事件的参与者,将其与事件结合并返回一个EventResponse
stuct。
描述该问题的一种非特定场景的方式是“如何Result<Vec<T>, err>
从嵌套的 flat_map 中获取Result<Vec<T>, err>
,它的嵌套地图为Result<T, err>
”
下面是我正在使用的代码的抽象/简化版本,它给了我与实际代码相同的错误。
struct Event {
id: usize,
}
#[derive(Debug)]
struct EventResponse {
id: usize,
participants: Vec<i32>,
}
fn main() {
let orgs = vec![1, 3, 14, 12];
let events: Result<Vec<EventResponse>, &str> = orgs
.iter()
.flat_map::<Result<Vec<EventResponse>, &str>, _>(|org_id| {
get_events_for(*org_id)
.map_err(|_| "That Org id does not exist")
.map(|events| {
events
.iter()
.map::<Result<EventResponse, &str>, _>(|event| {
get_event_with_participants(event)
.map(|event_response| event_response)
.map_err(|_| "Participants for that event were not found")
})
.collect()
})
})
.collect();
}
fn get_events_for(id: usize) -> Result<Vec<Event>, ()> {
// pretend we are checking against a database of existing org ids, if the org id does not exist, then return an error
if id == 3 {
Ok(vec![Event { id }])
} else {
Err(())
}
}
fn get_event_with_participants(event: &Event) -> Result<EventResponse, ()> {
//pretend the participants are fetched from a database
let foundParticipants = true;
if foundParticipants {
Ok(EventResponse {
id: event.id,
participants: vec![1, 2, 5],
})
} else {
Err(())
}
}
类型注释将显示每个阶段预期返回的内容。我希望events
是类型Result<Vec<EventResponse>, &str>
,但我收到 2 个错误:
error[E0277]: a collection of type `std::vec::Vec<EventResponse>` cannot be built from an iterator over elements of type `std::result::Result<EventResponse, &str>`
--> example.rs:27:26
|
27 | .collect()
| ^^^^^^^ a collection of type `std::vec::Vec<EventResponse>` cannot be built from `std::iter::Iterator<Item=std::result::Result<EventResponse, &str>>`
|
= help: the trait `std::iter::FromIterator<std::result::Result<EventResponse, &str>>` is not implemented for `std::vec::Vec<EventResponse>`
error[E0277]: a collection of type `std::result::Result<std::vec::Vec<EventResponse>, &str>` cannot be built from an iterator over elements of type `std::vec::Vec<EventResponse>`
--> example.rs:30:10
|
30 | .collect();
| ^^^^^^^ a collection of type `std::result::Result<std::vec::Vec<EventResponse>, &str>` cannot be built from `std::iter::Iterator<Item=std::vec::Vec<EventResponse>>`
|
= help: the trait `std::iter::FromIterator<std::vec::Vec<EventResponse>>` is not implemented for `std::result::Result<std::vec::Vec<EventResponse>, &str>`
编辑:无法修改get_events_for
功能,但是,如果有帮助,可以修改功能。get_event_with_participants