Tilded
Tilded

Reputation: 431

Avoiding redundant work when matching and parsing

I'm using match to see if string input is a position, and if it does, convert it to a tuple. For example, "B6" would become (1, 5). I have the functions is_pos to math the right input and parse_pos to transform it, so each match needs to perform string parsing twice.

fn main() {
    let input = ""
    match input {
        "exit" => return,
        _ if is_pos(input) => parse_pos(input),
        _ => (0, 0),
    };
}

fn is_pos(str: &str) -> bool {
    // string processing
    true
}

fn parse_pos(str: &str) -> u32 {
    // the same string processing
    5
}

I'd to have one function that returns an Option. Then the match would select the Option if it wasn't none, and I could unwrap it without needing to redo the string parsing.

Is this possible with match, or should I go back to using if statements?

Upvotes: 1

Views: 165

Answers (1)

kennytm
kennytm

Reputation: 523414

There is no elegant way to save the intermediate result of the if clause. Yes you could go back to an if statement.

if input == "exit" {
    return;
}
let pos = parse_pos(input).unwrap_or((0, 0));

You could still use a match like this:

let pos = match input {
    "exit" => return,
    _ => parse_pos(input).unwrap_or((0, 0)),
};

(Note that the early-return here does not really stand out. Could be a problem for future readers.)

Upvotes: 3

Related Questions