Search code examples
rustiteratorfluent

Is there an Iter::find() equivalent that accepts a predicate that may fail?


Consider this function:

pub async fn has_table(&mut self, name: &str) -> Result<bool, sqlx::Error> {
    for r in self
        .metadata
        .get_tables(&mut self.connection, name, &Vec::new(), None, None)
        .await?
    {
        if r.try_get::<'_, &'_ str, &'_ str>("name")? == name {
            return Ok(true);
        }
    }
    Ok(false)
}

I would like to rewrite its body in fluent style, but I don't know how to handle the fact that r.try_get() may fail. Ideally I would like to be able to write something like:

Ok(
    match self
        .metadata
        .get_tables(&mut self.connection, name, &Vec::new(), None, None)
        .await?
        .iter()
        .find(|r| r.try_get::<'_, &'_ str, &'_ str>("name")? == name)
    {
        Some(_) => true,
        None => false,
    },
)

which is obviously invalid because the argument to Iter::find() must return bool.


Solution

  • try_find exists but it currently is unstable.

    Since you already have an implementation based on a for loop I don't think there's a more concise way to achieve this until try_find is stable.