Is it bad style to match a bool?


#1

I used clippy for the first time today and ran into a warning for using match on a bool, rather than an if/else.

The reason I do this is that I align my braces, so it’s more concise to write:

match condition
{
    true => do_something(),
    false => do_something_else()
}

than…

if condition
{
    do_something();
}
else
{
    do_something_else();
}

Is there a good reason to prefer the second version to the first, and is the first really horrible and confusing?

Thanks!


#2

Well, I would say that the second solution is better because you don’t have to explitely say true or false, but Rust’s obligation to put {} for if else statements gets anoying when you have only one line inside.

I did not find anything regarding this and would be OK with both solutions. Plus, if anyone isn’t happy with your match, it’s a simple fix.


#3

It’s considered bad style to align the braces, so the idiomatic way is


if condition {
    do_something();
} else {
    do_something_else();
}

But, of course, you can always do what you want!


#4

I would rather phrase it as “unidiomatic”: Rust community overwhelmingly uses K&R style for braces. There’s nothing inherently good or bad in any particular style.


#5

Well, except for the following one :smiling_imp:

if condition                                    {
    do_something()                             ;}
else                                            {
    do_something_else()                        ;}

#6

Yes, I mirrored the language of the OP, but generally prefer "unidiomatic"
as well. Thanks <3


#7

For years I’ve had the color scheme of my editor set to show punctuation at 40% opacity. I’ll reset this now so when I come across this style you quoted I’ll be sure to notice it so I can get rightfully mad.


#8

Think the fact I felt I had to ask this question in the first place has convinced me to just use if/else.

Not sure I can bring myself to change brace style yet though D:


#9

Rustfmt should have a mode for that.