Skip to content

Inline if .. else expression #452

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
barosl opened this issue Oct 13, 2015 · 9 comments
Closed

Inline if .. else expression #452

barosl opened this issue Oct 13, 2015 · 9 comments

Comments

@barosl
Copy link

barosl commented Oct 13, 2015

if .. else is sometimes used in lieu of the ternary operator in C, so it might be a good idea to preserve the original intention if the programmer wrote a short if .. else expression in a single line.

A wild case found in rust-lang/rust#28988:

if align <= MIN_ALIGN { 0 } else { mallocx_align(align) }

was converted into:

if align <= MIN_ALIGN {
    0
} else {
    mallocx_align(align)
}

which looks a bit more verbose. Is this an intended behavior?

Hmm, well, looking at the code again, the latter also seems OK to me... Now I'm not sure which side I'm in. Maybe this should be exposed as a configuration option?

@nrc
Copy link
Member

nrc commented Oct 13, 2015

It is intended, but it's a style that's often requested, so we should probably have an option for it.

(I thought there was an issue for this already, but I couldn't find one).

@mseri
Copy link

mseri commented Oct 13, 2015

+1 on this. There are some libraries in rust-lang in which this change is made all-over the place, even for very short lines (e.g. libfmt_macros, although in many cases I prefer rustfmt style).

@marcusklaas
Copy link
Contributor

This is already possible by setting single_line_if_else to true in the config!

@marcusklaas
Copy link
Contributor

@nrc
Copy link
Member

nrc commented Oct 13, 2015

Ha! That is why I couldn't find an issue :-)

@mseri
Copy link

mseri commented Oct 13, 2015

Ah cool! Thanks!!

@wfxr
Copy link

wfxr commented Dec 26, 2019

@marcusklaas Was option single_line_if_else removed?

$ rustfmt --version
rustfmt 1.4.11-nightly (1838235 2019-12-03)
$ rustfmt main.rs
Warning: Unknown configuration option `single_line_if_else`

@marcusklaas
Copy link
Contributor

I do not know. I haven't been involved with this project for a long time.

@enigmartyr
Copy link

even with single_line_if_else if the if-else statement is your return value then the formatter will still open the statement up unless you explicitly use the return keyword (which I believe isn't idiomatic, ironically)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants