Is there a way to prevent gofmt from converting code functions to multiline without disabling gofmt entirely?

2.6k Views Asked by At

I'm using Vim version 8.1.1401 with go version go1.13.1 linux/amd64. I'm trying to disable gofmt from putting all if statement brackets on a new line, for instance:

if thing { return }

is converted to

if thing {
   return
}

The only way I've discovered to disable this is by setting:

let g:go_fmt_autosave = 0

however, this disables gofmt altogether. Can I do this somehow without disabling gofmt altogether?

2

There are 2 best solutions below

0
On

Funny that you can trick that formatter with comments. Here's an example

for VERY_LONG_VARIABLE_NAME_HAHAHAHAHAHAHAH := uint(0); //
VERY_LONG_VARIABLE_NAME_HAHAHAHAHAHAHAH < size;  //
VERY_LONG_VARIABLE_NAME_HAHAHAHAHAHAHAH++ {
}

Without // it'd format it in a single line

0
On

In a word: No.

gofmt is, by design, opinionated, and non-configurable. Go is unapologetic about this. From the Go Proverbs:

Gofmt's style is no one's favorite, yet gofmt is everyone's favorite.

If it were possible to configure gofmt to do this, or anything else, it would immediately lose the majority of its value, which is that it settles all silly formatting arguments once and for all.

Learn to love this. As the linked video clip explains, the vast majority of experienced Go programmers love this about Go. I expect in time you will, too.


And as a side note, in your particular example, there's good reason gofmt chose this format: A single-line if statement is much less readable. By putting the action on a separate line, it is immediately obvious, to any reader, what the code does. Consider these two alternatives:

if foo && (bar > baz) || quxx { return foo && bar }

vs

if foo && (bar > baz) || quxx {
    return foo && bar
}

The cognitive load to parse the first example is much greater than the second. Even in a very simplified example such as if x { return }, there's never any harm in splitting the lines, and arguably it still improves readability due to greater consistency.