rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
6.04k stars 888 forks source link

single line if-else not appied if expression is used as implicit return #5593

Closed cyqsimon closed 2 years ago

cyqsimon commented 2 years ago

TLDR:

// single line expected; got multi line
fn is_zero(n: i32) -> bool {
    if n == 0 {
        true
    } else {
        false
    }
}

To reproduce:

Create a new cargo project with default rustfmt settings, paste in this function, and format document.

Expected:

fn is_zero(n: i32) -> bool {
    if n == 0 { true } else { false }
}

Actual:

fn is_zero(n: i32) -> bool {
    if n == 0 {
        true
    } else {
        false
    }
}

Misc:

Adding explicit return triggers single line mode, which shows it's not related to single_line_if_else_max_width:

fn is_zero(n: i32) -> bool {
    return if n == 0 { true } else { false };
}

Versions:

rustfmt 1.5.1-stable (897e375 2022-11-02) on Linux 6.0.6 x86_64

ytmimi commented 2 years ago

Thanks for reaching out.

There was some work done in https://github.com/rust-lang/rustfmt/pull/5509 to expand the docs on single_line_if_else_max_width.

The explicit return seems like an interesting case.

calebcartwright commented 2 years ago

tl;dr - duplicate of (primary) item #4351 with more detail in the first half of from https://github.com/rust-lang/rustfmt/issues/4351#issuecomment-663782224. You can set version=Two to get the desired behavior if you're able to work on nightly, otherwise it's something that just has to be accepted due to the stability guarantees