iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🙆

How to Format Go Source Code

に公開

How to Format Go Source Code

In this article, I will introduce how to use Go's standard formatter, go fmt, and how to configure automatic formatting in VSCode.

1. How to Use go fmt

1.1. Applying to a Single File

To format a specific file, use the following command:

go fmt ./myfile.go

Example (Before formatting)

package main

import "fmt"

func main() {
fmt.Println("Hello, World!")
  fmt.Println(   "Hello, World!"    )
var x int = 10
  if(x> 5){
fmt.Println("test")
}else{
fmt.Println("test")
  }
}

Example (After formatting)

package main

import "fmt"

func main() {
	fmt.Println("Hello, World!")
	fmt.Println("Hello, World!")
	var x int = 10
	if x > 5 {
		fmt.Println("test")
	} else {
		fmt.Println("test")
	}
}

1.2 Applying Recursively to .go Files in a Specific Directory

To recursively format .go files within a specific directory, use ....
Below is an example of applying it recursively to .go files under the current directory.

go fmt ./...

2. How to Automatically Apply in VSCode

2.1 Install the "Go" Extension for VSCode

In VSCode, you can automatically run go fmt when you save a file (Ctrl + S).

Please install the "Go" extension from the VSCode Extensions.
After the installation is complete, open a file, intentionally mess up the formatting, and then save the file. The source code should be automatically formatted.

Discussion