Why does the vscode golang plugin remove spaces around operators on save?

Viewed 575

If it matters, I've been writing code for many years, but I'm only now exploring golang and vscode at the same time.

On my Linux box, I installed vscode (1.56.2) and the golang plugin (0.25.1).

I've been stepping through some simple golang tutorials, and I noticed a curious thing that happened when I saved a file I had edited.

This is the line I had:

out = append(out, base + v)

When I saved it, it went to this:

out = append(out, base+v)

It removed the spaces around the "+" operator. I went searching through the vscode and golang extension settings, and I found almost nothing about what it will do on save.

In fact, in Settings, I have "Format On Save" UNchecked.

So, what is doing this, and why? Do I have any ability to configure this?

2 Answers

So, what is doing this, and why?

Your editor runs the the gofmt command on save. The command uses space to show operator precedence.

The following snippet is formatted with the gofmt command. Notice how operands are closer to the higher precedence operators.

fmt.Println(a + b + c + d)
fmt.Println(a * b * c * d)
fmt.Println(a + b*c + d)
fmt.Println(a*b + c*d)

The gofmt command removes the spaces around the + in the question because the + has precedence over the ,.

This has nothing to do with VScode. If you have this file:

package main
import "fmt"

func main() {
   var a []int
   a = append(a, 1 + 2)
   fmt.Println(a)
}

Running gofmt file.go gives you:

package main

import "fmt"

func main() {
        var a []int
        a = append(a, 1+2)
        fmt.Println(a)
}
Related