Filter a vector depending on async function

Hello

I am trying to filter a vector of a struct depending on a async function.

Struct:

#[derive(Deserialize, Serialize, Clone)]
pub struct Restaurant {
...
}

This is my async function:

pub async fn is_currently_open(&self, mysql: &web::Data<MySQL>) -> bool {...}

Code:

let mut restaurants: std::vec::Vec<Restaurant> = std::vec::Vec::new();

// I push some Restaurants in this vec here
//....

// Now I need to filter them, I tried this:
restaurants = restaurants
                .into_iter()
                .filter_map(|r| async move {
                    if r.is_currently_open(&mysql).await {
                        Some(r)
                    } else {
                        None
                    }
                })
                .collect()
                .await;

Error:

error[E0308]: mismatched types
   --> src/data.rs:474:33
    |
474 |                   .filter_map(|r| async move {
    |  _________________________________^
475 | |                     if r.is_currently_open(&mysql).await {
476 | |                         Some(r)
477 | |                     } else {
478 | |                         None
479 | |                     }
480 | |                 })
    | |_________________^ expected enum `std::option::Option`, found opaque type
    |
   ::: /Users/niel/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/future/mod.rs:72:43
    |
72  |   pub const fn from_generator<T>(gen: T) -> impl Future<Output = T::Return>
    |                                             ------------------------------- the found opaque type
    |
    = note:     expected enum `std::option::Option<_>`
            found opaque type `impl futures::Future<Output = std::option::Option<Restaurant>>`
help: try wrapping the expression in `_::_serde::__private::Some`
    |
474 ~                 .filter_map(|r| _::_serde::__private::Some(async move {
475 |                     if r.is_currently_open(&mysql).await {
476 |                         Some(r)
477 |                     } else {
478 |                         None
479 |                     }
  ...

I already tried making the vector of type Option<Restaurant> but that also did not work.

How would I do this?

You'll probably want to convert your iterator into a stream (tokio_stream - Rust) I think (it's 2am)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.