Skip to content

if/else closures with return type removes curly brackets #4577

Closed
@bombsimon

Description

@bombsimon

Describe the bug

if/else in closure with return type removes required curly brackets. This doesn't seem to be too uncommon to me but I didn't find any issues for this bug. Sorry if this is already known, if so please close this issue and refer to the original.

To Reproduce

fn main() {
    let s: String = "ABAABBAA".chars().map(|c| -> char {
        if c == 'A' {
            '0'
        } else {
            '1'
        }
    }).collect();
    
    println!("{}", s);
}

After running rustfmt on this code, it becomes

fn main() {
    let s: String = "ABAABBAA"
        .chars()
        .map(|c| -> char if c == 'A' { '0' } else { '1' })
        .collect();

    println!("{}", s);
}

This is no longer possible to compile and gives the following error:

error: expected `{`, found keyword `if`
 --> src/main.rs:4:26
  |
4 |         .map(|c| -> char if c == 'A' { '0' } else { '1' })
  |                          ^^------------------------------
  |                          |
  |                          expected `{`
  |                          help: try placing this code inside a block: `{ if c == 'A' { '0' } else { '1' } }`

error: aborting due to previous error

The following example will not break the code:

fn main() {
    let s: String = "ABAABBAA"
        .chars()
        .map(|c| -> char {
            if c == 'A' {
                return '0';
            }

            '1'
        })
        .collect();

    println!("{}", s);
}

Expected behavior

The code to be formatted, but still working

Meta

  • rustfmt version: rustfmt 1.4.24-stable (eb894d5 2020-11-05)
  • From where did you install rustfmt?: rustup
  • How do you run rustfmt: rustftm <filename> or via Rust vim plugin

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions