Idiomatic pattern for boolean option

Hi! I'm pretty new to learning Rust and I'm experimenting with a few patterns, looking for the most idiomatic/elegant way to solve problems. Today I came across one where I can find a solution, but I'm not sure if there's a better way.

The problem I'm trying to solve: Write some content to a file and, optionally, compress that file.

My solution, conceptually: Take advantage of the Write trait and wrap the object in a GzEncoder if compression is desired.

I've implemented it in the playground here: Rust Playground

The pattern I'm looking for boils down to these lines:

    let mut file: Box<dyn Write> = match compress {
        true => Box::new(GzEncoder::new(file, Compression::default())),
        false => Box::new(file),
    };

Given a boolean compress, is this the most idiomatic way to solve the problem?

1 Like

That seems reasonable enough to me. You can avoid the Box like this:

let mut gz_file;
let mut normal_file;

let file: &mut dyn Write = match compress {
    true => { gz_file = GzEncoder::new(file, Compression::default()); &mut gz_file }
    false => { normal_file = Box::new(file); &mut normal_file }
};
3 Likes

The idiomatic notation for matching on a bool is the if expression, of course.

4 Likes

Fascinating, thank you! So the reason this works is because those two mutable variables you declare are in the outer scope and by returning references I'm doing the same as box (making them a pointer)? Is there a distinction here, like could the reference point to the stack? Or will it always end up being the same compiled code?

:man_facepalming: Of course it is. I think I've fallen in love with the exhaustive match of Rust a little bit too much... Thanks for the suggestion!

Not the same. They are stored on the stack, like any local variable, and the reference points to this location on the stack, too.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.