Formatting code with GOFMT

Source: Internet
Author: User

For a programming language, code formatting is one of the most controversial issues, and different developers may have different coding styles and habits, but if all developers can write code in the same format, developers can focus their precious time on the issues that the language solves.

GOFMT Introduction

Golang's development team developed a unified official code style and launched the Gofmt tool (GOFMT or go FMT) to help developers format their code into a unified style. GOFMT is a CLI program, will first read the standard input, if the file path is passed, the file will be formatted, if passed in a directory, will format all the. Go files in the directory, if not pass parameters, will format all the. Go files in the current directory.

Gofmt default does not simplify the code, using the-s parameter can be turned on to simplify the code functionality, in particular, the following conversions:

    • Eliminate unnecessary type declarations for arrays, slices, and map initialization:
如下形式的切片表达式:    []T{T{}, T{}}将被简化为:    []T{{}, {}}
    • Unnecessary index designations when removing array slice operations
如下形式的切片表达式:    s[a:len(s)]将被简化为:    s[a:]
    • Non-essential variable assignment when removing iterations
如下形式的迭代:    for x, _ = range v {...}将被简化为:    for x = range v {...}如下形式的迭代:    for _ = range v {...}将被简化为:    for range v {...}

The list of gofmt command parameters is as follows:

usage: gofmt [flags] [path ...]  -cpuprofile string        write cpu profile to this file  -d    display diffs instead of rewriting files  -e    report all errors (not just the first 10 on different lines)  -l    list files whose formatting differs from gofmt's  -r string        rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')  -s    simplify code  -w    write result to (source) file instead of stdout

As you can see, the GOFMT command also supports custom rewrite rules that use the-R parameter to pass in the rules in the format of replacement, pattern, and so on.

A Golang program with the following content is stored in the Main.go file.

package mainimport "fmt"func main() {   a := 1   b := 2   c := a + b   fmt.Println(c)}

Use the following rules to format the above code.

gofmt -r "a + b -> b + a"

The results of the formatting are as follows.

package mainimport "fmt"func main() {   a := 1   b := 2   c := b + a   fmt.Println(c)}

* Note: GOFMT uses tab to represent indentation, and there is no limit to the width of the line, and GOFMT does not force the code to be formatted back to a line if the code is manually wrapped.

Go FMT and Gofmt

GOFMT is a standalone CLI program, and Go has a go fmt command, the Go FMT command is a simple package of gofmt.

usage: go fmt [-n] [-x] [packages]Fmt runs the command 'gofmt -l -w' on the packages namedby the import paths. It prints the names of the files that are modified.For more about gofmt, see 'go doc cmd/gofmt'.For more about specifying packages, see 'go help packages'.The -n flag prints commands that would be executed.The -x flag prints commands as they are executed.To run gofmt with specific options, run gofmt itself.See also: go fix, go vet.

The Go FMT command itself has only two optional parameters,-N, and-x,-n only prints out the internal command to go to FMT, the-x command prints out the Go FMT command and executes it, and if more granular configuration is required, the GOFMT command needs to be executed directly.

The go FMT added the-l-w parameter when calling Gofmt, which is equivalent to executing gofmt -l -w .

Configuring GOFMT in Goland

Goland is the JetBrains company launched the go Language IDE, is a powerful, easy to use products.

In Goland, you can add a file watcher to call gofmt for code formatting When a change occurs, by clicking Preferences, Tools, file watchers, click the plus sign to add a go In the FMT template, the Go fmt template, which is preset in Goland, uses the Go FMT command, replaces it with GOFMT, and then adds the-l-w-s parameter to the parameter, enabling the Code simplification feature. Once the configuration is added, Goland will execute code formatting when the source is saved.

Reference articles

https://golang.org/cmd/gofmt/

Https://golang.org/doc/effective_go.html

Https://openhome.cc/Gossip/Go/gofmt.html

Https://github.com/hyper0x/go_command_tutorial/blob/master/0.9.md

Click to follow the column Golang private cuisine

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.