What is the point of an Infallible Result, over just returning the Ok() branch?
Asked Answered
T

1

9

The canonical example of a Warp rejection handler is

async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {

But what's the advantage of a Result<ok, err> such that the err is Infallible and can never be reached? Why not just return an impl Reply?

Top answered 4/6, 2021 at 2:19 Comment(1)
It's mostly useful for generic programming, e.g. where a trait can return an error using an associated type, but may not actually represent a fallible operation.Anechoic
D
19

It usually means one of two things:

  • The function is part of a trait, and the trait declaration indicates that the method can fail and return a Result<T, E>. Now, some implementations of that trait might happen not to have a fail path, and use an Infallible-like type for E.

    A standard library example of this is the FromStr trait. FromStr can obviously fail when implemented on u32, but not when implemented on String. Therefore impl FromStr for String uses std::convert::Infallible for its error case.

  • The function is going to be used in a context that expects a fallible function.

    This is the case in your example. handle_rejection is passed to warp::Filter::recover, which expects a fallible function. This makes sense as not all errors are recoverable, therefore recover might still have to deal with these.

    Now, this is a toy example that happens to be able to handle all errors, and therefore use Infallible.

Divinize answered 4/6, 2021 at 11:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.