Search code examples
gogofmt

Inconsistent formatting of Go code?


Here are some example code:

func main() {
    os.MkdirAll(outDir + id, 0755)
    os.Create(outDir + id + "/txt")
    os.OpenFile(outDir + id + "/" + ".tmp", os.OWRONLY|os_APPEND)
    os.Stat(outDir + id + "/.tmp")
}

The following is the output after formatting with either go fmt or pressing Format on the Go Playground:

func main() {
    os.MkdirAll(outDir+id, 0755)
    os.Create(outDir + id + "/txt")
    os.OpenFile(outDir+id+"/"+".tmp", os.OWRONLY|os_APPEND)
    os.Stat(outDir + id + "/.tmp")
}

Spaces in os.MkdirAll() and os.OpenFile() are removed while they are untouched in os.Create() and os.Stat(). I would expect that formatting to be identical.

Why is this happening?


Solution

  • See: https://github.com/golang/go/issues/12720

    gofmt uses spaces around binary expressions to express binding strength. Depending on nesting level, spaces are removed.

    You could also find these easily by searching for "gofmt inconsistent spaces". See also issue #1206, #1848, #1861, #7880, and #11497.