以一个简单的例子说明一下go中比较有用的小工具
1. 小工具
1.1 生成一个main.go脚本
jeffreyguan@localhost ~$ cat > main.go
package main
import "fmt"
func main() { fmt.Println("Hello, Jeffrey Guan") }
jeffreyguan@localhost ~$ cat main.go 130 ↵
package main
import "fmt"
func main() { fmt.Println("Hello, Jeffrey Guan") }
1.2. gofmt main.go
jeffreyguan@localhost ~$ gofmt main.go
package main
import "fmt"
func main() { fmt.Println("Hello, Jeffrey Guan") }
1.3. gofmt -d main.go
jeffreyguan@localhost ~$ gofmt -d main.go
diff -u main.go.orig main.go
--- main.go.orig 2019-08-17 21:42:13.000000000 +0800
+++ main.go 2019-08-17 21:42:13.000000000 +0800
@@ -1,5 +1,5 @@
package main
-import "fmt"
-func main() { fmt.Println("Hello, Jeffrey Guan") }
+import "fmt"
+func main() { fmt.Println("Hello, Jeffrey Guan") }
1.4. gofmt -w main.go
jeffreyguan@localhost ~$ gofmt -w main.go
jeffreyguan@localhost ~$ cat main.go
package main
import "fmt"
func main() { fmt.Println("Hello, Jeffrey Guan") }
1.5. go build
jeffreyguan@localhost ~$ go build main.go
jeffreyguan@localhost ~$ file main
main: Mach-O 64-bit executable x86_64
按平台生成可执行文件
jeffreyguan@localhost ~$ GOOS=windows go build main.go
jeffreyguan@localhost ~$ file main.exe
main.exe: PE32+ executable (console) x86-64 (stripped to external PDB), for MS Windows
1.6. go get
go get github.com/golang/example/hello
1.7. go list
jeffreyguan@localhost ~/lanjie$ cat main.go
// demo is also demo
package main
import "fmt"
func main() { fmt.Println("Hello, Jeffrey Guan") }
jeffreyguan@localhost ~/lanjie$ go list -f '{{ .Name }}'
main
jeffreyguan@localhost ~/lanjie$ go list -f '{{ .Name }}: {{ .Doc}}'
main: demo is also demo
jeffreyguan@localhost ~/lanjie$ go list -f '{{ .Name }}: {{ .Doc}}'
main: demo is also demo
jeffreyguan@localhost ~/lanjie$ go list -f '{{ .Imports }}'
[fmt]
jeffreyguan@localhost ~/lanjie$ go list -f '{{ join .Imports "\n"}}' fmt
errors
internal/fmtsort
io
math
os
reflect
strconv
sync
unicode/utf8
jeffreyguan@localhost ~/lanjie$ go list -f '{{ .Doc }}' fmt
Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
1.8. do doc
jeffreyguan@localhost ~/lanjie$ go doc fmt
jeffreyguan@localhost ~/lanjie$ go doc fmt Println
func Println(a ...interface{}) (n int, err error)
Println formats using the default formats for its operands and writes to
standard output. Spaces are always added between operands and a newline is
appended. It returns the number of bytes written and any write error
encountered.
# 在本地启动go doc
jeffreyguan@localhost ~/lanjie$ godoc -http=localhost:6060