> For the complete documentation index, see [llms.txt](https://denglj.gitbook.io/essential-go/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://denglj.gitbook.io/essential-go/common-standard-libraries/56-the-go-command/go-fmt.md).

# go fmt

为了保持代码的一致性并消除代码格式化方面的争论，Go提供了go fmt工具。

格式化一个文件：`go fmt main.go`&#x20;

格式化一个文件夹下的所有文件：`go fmt myProject`&#x20;

您还可以使用`gofmt -s`（而不是`go fmt`）来尝试简化代码。

`gofmt`（不是`go fmt`）也可以用于重构代码。 它理解Go语法，因此它比搜索和替换功能更强大。例如，给定下列程序（main.go）：

```go
package main

type Example struct {
    Name string
}

func (e *Example) Original(name string) {
    e.Name = name
}

func main() {
    e := &Example{"Hello"}
    e.Original("Goodbye")
}
```

您可以使用`gofmt`将`Original`方法重构为`Refactor`：

```bash
gofmt -r 'Original -> Refactor' -d main.go
```

将产出如下diff：

```bash
-func (e *Example) Original(name string) {
+func (e *Example) Refactor(name string) {
 	e.Name = name
 }

 func main() {
 	e := &Example{"Hello"}
-	e.Original("Goodbye")
+	e.Refactor("Goodbye")
 }
```
