2

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?

TylerH
  • 20,799
  • 66
  • 75
  • 101
darthguinea
  • 115
  • 3
  • 7
  • 7
    Go is an opinionated language and so is its style enforced by gofmt. If you're going to use your own style in Go, other gophers are going to be mad at you. Make peace with gofmt. There's no everyone's favorite, but gofmt's style has been accepted by the Go community (it's "everyone's favorite"), and more: it's the expected style. – icza Nov 01 '19 at 11:24
  • 4
    gofmt has no options or configuration, by design. That would defeat the purpose of a globally consistent code style. What icza said: get used to it. – Peter Nov 01 '19 at 11:30
  • Those comments both sound like good answers. Not sure why they were posted as comments instead. cc @icza – TylerH Nov 01 '19 at 14:33

1 Answers1

1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189