Skip to content

What is the best way to achieve Rust question mark operator-like behavior #203

Answered by chriskrycho
snaumov asked this question in Q&A
Discussion options

You must be logged in to vote

Great question! There isn’t really any much better translation than that, because JS doesn’t have native pattern matching. Strictly speaking, you want to do roughly this so that you can get a new error of the correct type, rather than doing an unsafe cast (TS playground):

import { Result } from 'true-myth/result';

function demoEarlyReturn(result: Result<string, Error>): Result<number, Error> {
    if (result.isErr()) {
        return Result.err(result.error);
    }

    const { value } = result;
    return Result.ok(value.length);
}

This isn’t great in performance-sensitive code, given the extra allocation… but the unfortunate reality is that our Maybe and Result aren’t great in performa…

Replies: 1 comment 6 replies

Comment options

You must be logged in to vote
6 replies
@chriskrycho
Comment options

@snaumov
Comment options

@Nick-Mazuk
Comment options

@chriskrycho
Comment options

@chriskrycho
Comment options

Answer selected by chriskrycho
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #201 on November 26, 2021 21:22.