Polishing Rust: Boxing and Unboxing Results

A new rustlang article! This week, I talk about how to simplify code where you have to match on a Result and then return a Result.

1 Like

Quibble: I wouldn't use the words "boxing" and "unboxing" in the title since these have specific technical meanings when discussing Rust.

6 Likes

FWIW, I personally find the outer map_or harder to read than the outer if let because the body of the closure is long (it's basically the rest of the original function's body). So I don't actually like the end result better.

I think it would have been more beneficial to extract the call to graph_ahead_behind() into a variable instead, and reduce nesting by means of an early return. There's also map_err with which you could spare the branch.name()?.unwrap() and stick to the original error reporting approach:

fn get_branch_ahead_behind(&self, branch: Branch) -> anyhow::Result<AheadBehind> {
    let upstream = match branch.upstream() {
        Ok(upstream) => upstream,
        Err(_) => return Ok(NotTracking),
    };

    let ab = self.graph_ahead_behind(
        branch.get().target().unwrap(),
        upstream.get().target().unwrap(),
    );

    ab.map(|ab| match ab {
        (0, 0) => Ok(UpToDate),
        (ahead, 0) => Ahead(ahead),
        (0, behind) => Behind(behind),
        (ahead, behind) => AB(ahead, behind),
    }).map_err(|e| {
        anyhow!("Could not get upstream info: {}", e)
    })
}
1 Like

You are not wrong. In fact, I realized this... right after I published the article :man_facepalming:

1 Like