为什么 vscode 的 golang 插件在保存时会删除运算符周围的空格?

huangapple go评论112阅读模式
英文:

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

问题

如果有关系的话,我已经写了很多年的代码,但现在我同时在探索golang和vscode。

在我的Linux系统上,我安装了vscode(1.56.2)和golang插件(0.25.1)。

我一直在进行一些简单的golang教程,我注意到当我保存编辑过的文件时发生了一件奇怪的事情。

这是我原本的代码行:

out = append(out, base + v)

当我保存后,它变成了这样:

out = append(out, base+v)

它去掉了“+”运算符周围的空格。我在vscode和golang扩展设置中进行了搜索,几乎找不到关于保存时会执行什么操作的信息。

实际上,在设置中,我没有勾选“保存时格式化”。

那么,是什么在做这个操作,为什么会这样?我有没有能力进行配置?

英文:

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?

答案1

得分: 4

所以,这是怎么回事,为什么要这样做?

你的编辑器在保存时运行gofmt命令。该命令使用空格来显示运算符优先级。

以下代码片段是使用gofmt命令格式化的。请注意,操作数与优先级较高的运算符更接近。

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

gofmt命令会删除问题中+周围的空格,因为+的优先级高于,

英文:

> 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 ,.

答案2

得分: 0

这与VScode无关。如果你有这个文件:

package main
import "fmt"

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

运行gofmt file.go会得到:

package main

import "fmt"

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

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)
}

huangapple
  • 本文由 发表于 2021年6月1日 04:08:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/67779685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定