【Golang】Linters - gofmt

Posted by 西维蜀黍 on 2021-07-28, Last Modified on 2021-09-21

Introduction

Gofmt is a tool that automatically formats Go source code.

Gofmt’d code is:

  • easier to write: never worry about minor formatting concerns while hacking away,
  • easier to read: when all code looks the same you need not mentally convert others’ formatting style into something you can understand.
  • easier to maintain: mechanical changes to the source don’t cause unrelated changes to the file’s formatting; diffs show only the real changes.
  • uncontroversial: never have a debate about spacing or brace position ever again!

Format your code

We recently conducted a survey of Go packages in the wild and found that about 70% of them are formatted according to gofmt’s rules. This was more than expected - and thanks to everyone who uses gofmt - but it would be great to close the gap.

To format your code, you can use the gofmt tool directly:

$ gofmt -w yourcode.go

Or you can use the “go fmt” command:

$ go fmt path/to/your/package

To help keep your code in the canonical style, the Go repository contains hooks for editors and version control systems that make it easy to run gofmt on your code.

Format all files in a directory (including sub directories). You can put this in a git commit hook to run it every time you commit.

$ go fmt ./...

Git’s Pre-commit

Reference