官术网_书友最值得收藏!

Two useful Go tools

The Go distribution comes with a plethora of tools that can make your life as a programmer easier. The two most useful of them are gofmt and godoc.

Note that go tool itself can also invoke various tools: you can see a list of them by executing go tool.

The gofmt utility formats Go programs in a given way, which is really important when different people are going to work with the same code for a big project. You can find more information about gofmt at https://golang.org/cmd/gofmt/.

The following is a poorly formatted version of the hw.go program that is hard to read and understand:

$ cat unglyHW.go
package main
    
import
    "fmt"
    
// This is a demonstrative comment!
        func main() {
  fmt.Println("Hello World!")
    
}

Processing the previous code, which is saved as unglyHW.go with gofmt, generates the following easy to read and comprehend output:

$ gofmt unglyHW.go
package main
    
import "fmt"
    
// This is a demonstrative comment!
func main() {
      fmt.Println("Hello World!")
    
}

Remembering that the gofmt utility does not automatically save the generated output is important, which means that you should either use the -w option followed by a valid filename or redirect the output of gofmt to a new file.

The godoc utility allows you to see the documentation of existing Go packages and functions. You can find more information about godoc at http://godoc.org/golang.org/x/tools/cmd/godoc.

You are going to use godoc a lot as it is a great tool for learning the details of Go functions.

The following screenshot shows the output of the godoc command generated on a Terminal when asked for information about the Println() function of the fmt package:

The output of the godoc command

Another handy feature of godoc is that it can start its own web server and allow you to see its documentation using a web browser:

$ godoc -http=:8080  

The following screenshot shows the kind of output you get on a web browser after visiting http://localhost:8080/pkg/ while the previous command is running. You can use any port number you want, provided that it is not already in use:

Using the godoc utility from your web browser

The most important tool for a programmer is the editor they use for writing the source code. When I am on a Mac, I typically use the TextMate editor, but when I am on a different Unix machine, I prefer vi. Choosing an editor is not an easy task because you are going to spend a lot of time with it. However, any text editor will do the job as long as it does not put any control characters inside the source code files. The following screenshot shows the TextMate editor in action:

The TextMate editor showing the look of a some Go code
主站蜘蛛池模板: 土默特右旗| 酉阳| 稻城县| 乐昌市| 岑巩县| 阳西县| 分宜县| 牟定县| 沁水县| 稻城县| 苏尼特右旗| 迁安市| 内江市| 肥西县| 和田县| 吉安县| 新津县| 兴义市| 木兰县| 永仁县| 藁城市| 孝感市| 固安县| 南召县| 东辽县| 滨州市| 元朗区| 横峰县| 德格县| 楚雄市| 吴堡县| 锡林郭勒盟| 高碑店市| 通榆县| 子长县| 太湖县| 霍林郭勒市| 桃源县| 南召县| 上饶市| 闵行区|