• quantum_cantaloupe@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    1 year ago

    Typically the error track of the railroads analogy is implemented as a short circuit/return, so in effect this behavior IS an early return, but elegantly masked as though you are just handling the happy path.

    In rust, if you function returns a Result type (the Either type from the slides), you can track a ? On to the end of any function call that returns a Result. This gets de-sugared to a check for an error and returns from the function early if it is.

    At that point, the caller of the function gets to choose if they want to handle the potential failure of your function, or just let it bubble up further by using the ? operator. You end up with the behavior you’re describing, but with the benefit of errors handled by the type system and code that looks cleaner by just (explicitly) handling the happy path.