Skip to content

proposal: cmd/gofmt: A non-syntactic fix for error handling (permit single-line "if" statements) #74007

Closed as duplicate of#33113
@FBemf

Description

@FBemf

Proposal Details

The primary complaint with the typical go error handling pattern:

result, err := myFunc()
if err != nil {
    return nil, wrap(err)
}

is that two lines of meaningful code (lines 1 and 3) are taking up four lines of space. This isn't a syntax problem; this is a formatting problem. We could fix it like this:

result, err := myFunc()
if err != nil { return nil, wrap(err); }

I propose that gofmt permit single-line if statements. It doesn't need to create them proactively, but it should at least not alter them when it finds them.

There is some precedent for this. Gofmt already does not alter how arguments are broken up across multiple lines. All of the following are considered permissible by gofmt, and the programmer is expected to choose which of them to use on their own.

myFunc("first argument", "second argument", "third argument")
myFunc("first argument",
    "second argument", "third argument")
myFunc(
    "first argument",
    "second argument",
    "third argument",
)

With that in mind, I think allowing the programmer to choose between a one-line if err != nil and a three-line if err != nil is a moderate change that does not compromise gofmt's goal of standardizing code while leaving programmers with the option to write terser error handling if they wish.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions