This is a creation in Article, where the information may have evolved or changed.
In the go language, we have a lot of operations through go the command, such as we want to execute the Go file compilation, we need to use the go build command, in addition build to the command, there are many common commands, this time we have a unified introduction, the Common command has an understanding, This makes it easier for us to develop our go program.
Go Development Tools Overview
goThis tool, although the name is short, is actually very powerful, is a powerful development tool, let us Open the terminal to see what the tool has the ability.
➜~ GoGo is a tool for managing Go source code. Usage:go command [arguments]the commands are:build compile packages and dependencies clean remove O Bject files Doc show documentation for package or symbol ENV print GO environment information bug Start a bug report fix run Go tool fix on packages FMT run GOFMT in package sources gene Rate generate Go files by processing source get download and install packages and dependencies install Compile and install packages and dependencies list packages run compile and run Go program Test test Packages Tool run specified Go tool version print go version vet run Go tool Vet on Packagesuse ' Go help [command] ' For more information about a command. Additional help Topics:c calling between Go and C Buildmode description of build modes filetype F Ile Types Gopath Gopath environment variable Environment environment variables Importpath Import path Syntax packages DESCR Iption of package lists Testflag description of testing flags TestFunc description of testing FunctionsUse "go Help [Topic] "For more information on that topic.
You can see that the go supports a lot of subcommands and also supports viewing some "themes". We can use go help [command] or go help [topic] view some of the commands ' help, or information about a topic. Most go commands accept a full-path package name as a parameter, as we often use go build .
Go Build
go buildis a very common command that we can start compiling, compiling our packages and related dependencies into an executable file.
usage: go build [-o output] [-i] [build flags] [packages]
go buildThe use of a relatively concise, all parameters can be ignored, until only go build , this time means to use the current directory to compile, the following several commands are equivalent:
go buildgo build .go build hello.go
The above three kinds of writing, all use the current directory compiled meaning. Because we ignored it packages , we naturally compiled it using the current directory. From here we can also extrapolate that go build essentially a path is needed so that the compiler can find out which go files need to be compiled. packagesis actually a relative path, is relative to what we define GOROOT and GOPATH These two environment variables, so with packages This parameter, go build we can know which need to compile the go file.
go build flysnow.org/tools
This is the way to specify the package, which will explicitly compile our package. Of course we can also use wildcard characters.
go build flysnow.org/tools/...
3 dots indicate that all strings are matched, so go build all packages under the Tools directory are compiled.
go buildwhen it comes to compiling, it's not a cross-platform compilation, go provides a compile-chain tool that allows us to compile executable files for other platforms on any development platform.
By default, all are based on our current machine generated executable files, such as your Linux 64-bit, will generate Linux 64-bit executable files, such as my Mac, you can use Go env to view the compilation environment, the following interception of important parts.
➜ ~ go envGOARCH="amd64"GOEXE=""GOHOSTARCH="amd64"GOHOSTOS="darwin"GOOS="darwin"GOROOT="/usr/local/go"GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
Note that there are two important environment variables GOOS and Goarch, where GOOS refers to the target operating system, and its available values are:
- Darwin
- Freebsd
- Linux
- Windows
- Android
- Dragonfly
- NetBSD
- Openbsd
- Plan9
- Solaris
The 10 operating systems are supported altogether. Goarch refers to the architecture of the target processor and is currently supported by:
- Arm
- Arm64
- 386
- Amd64
- Ppc64
- Ppc64le
- Mips64
- Mips64le
- s390x
A total of 9 processors in the architecture, GOOS and goarch combination, supporting the generation of a variety of executable programs, the specific combination of reference https://golang.org/doc/install/source#environment. If we are going to generate executable programs for different platform architectures, just change these two environment variables, such as to build a Linux 64-bit program, the command is as follows:
GOOS=linux GOARCH=amd64 go build flysnow.org/hello
The first two assignments are changes to the environment variables, so the benefit is only valid for this run and will not change our default configuration.
These usages are almost enough for us to use, and more information about go build the user can be viewed through the following commands:
go help build
Go clean
When we compile, we generate the generated go build files, especially when we check in the code, and do not want to have our generated files checked into our git code base, we can manually delete the generated files, but sometimes forget, also very troublesome, accidentally commits to git. To solve this problem, we can use go clean it to clean up our compiled generated files, such as the generated executables, generate obj objects, and so on.
usage: go clean [-i] [-r] [-n] [-x] [build flags] [packages]
Usage and go build Basic, this is no longer a detailed example of the demonstration, can refer to go build the use of more about go clean the use, you can use the following command to view:
go help clean
Go run
go buildis to compile first and then we can execute the file to run our program, which takes two steps. go runThis command is a command that can be used to synthesize these two steps, saving the time we enter, and through the go run command we can see the results of the output directly.
➜~ go help runusage:go run [build flags] [-exec Xprog] gofiles ... [Arguments ...] Run compiles and runs the main package comprising the named Go source files. A Go source file is defined to being a file ending in a literal ". Go" suffix. By default, ' Go run ' runs the compiled binary directly: ' a.out arguments ... '. IF the-exec flag is given, ' go run ' invokes the binary using Xprog: ' Xprog a.out arguments ... '. IF the-exec flag is not given, GOOS or Goarch are different from the Systemdefault, and a program named Go_$goos_$goarch_e Xec can foundon the current search path, ' Go run ' invokes the binary using that program,for example ' go_nacl_386_exec a . Out arguments ... '. This allows execution ofcross-compiled programs if a simulator or other execution method isavailable. For more on build flags, see ' Go help build '.
go runcommand requires a go file as a parameter, the go file must contain the main package and the main function, so that it can run, other parameters and go build almost.
At run go run time, we can pass parameters to our program if necessary, such as:
package mainimport ( "fmt" "os")func main() { fmt.Println("输入的参数为:",os.Args[1])}
Open Terminal, enter the following command to execute:
go run main.go 12
Then we can see the output:
输入的参数为: 12
Go env
As we said earlier go build , we used the go env command to view our current go environment information.
➜ hello go help envusage: go env [var ...]Env prints Go environment information.By default env prints information as a shell script(on Windows, a batch file). If one or more variablenames is given as arguments, env prints the value ofeach named variable on its own line.
Use to go env view our Go environment information, easy for us to debug, troubleshooting, and so on, because sometimes we encounter some inexplicable problems, such as originally developed on the Mac, how to compile a Linux executable, and so on, when encountering such problems, first check our go environment information, See if there is any wrong configuration, step by step troubleshooting.
Go Install
From its name we are not difficult to guess what this command is doing, it and go build similar, but it can be compiled, the resulting executable file or library installed into the corresponding directory for use.
➜ hello go help installusage: go install [build flags] [packages]Install compiles and installs the packages named by the import paths,along with their dependencies.
Its usage is go build almost the same, if you do not specify a package name, the current directory is used. The directories that are installed are all agreed, and if the executable is generated, it is installed in the $GOPATH/bin directory, and if it is a referenced library, it is installed in the $GOPATH/pkg directory.
Go get
go getcommand, you can download and update the specified packages and dependent packages from the web, and compile and install them.
go get github.com/spf13/cobra
In the example above, we can download the go library directly from GitHub to our GOPATH workspace for our use. The entire source code project is downloaded, and will be compiled and installed according to them, and executed go install similarly.
go getWith support for most version control systems (VCS), such as our common Git, which is combined with package dependency management, we can import packages from the network directly for our use.
If we need to update a go project on the network, add the -u tag.
go get -u github.com/spf13/cobra
Similarly, enable -v tagging, you can see the progress of the download and more debugging information. For go get more usage of commands, you can use the following commands to view:
go help get
Go FMT
This is go to provide the most handsome command, it can format the layout of our source code and go to the same style, that is, the code style, so that we no longer need to put the curly braces to the end of the line or another line, indentation is the use of Space or tab and debated, all to us unified.
func main() { fmt.Println("输入的参数为:", os.Args[1]) }
For example, the above code, after we do go fmt the formatting, will become the following:
func main() { fmt.Println("输入的参数为:", os.Args[1])}
go fmtIt also accepts a package name as a parameter and, if not passed, uses the current directory. go fmtwill automatically format the code file and save it essentially is actually called gofmt -l -w this command, we look at gofmt the use of help.
➜ hello gofmt -h 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
go fmtFor us to unify the code style, so we found throughout the team collaboration, all the code is unified, like a person wrote. So our code must be formatted before committing to the Git library, and go fmt there are many editors that can automatically format the code for us when we save it.
Go vet
This command does not help developers write code, but it is also useful because it helps us to check common errors in our code.
- When a function call such as printf is called, the type matches the wrong argument.
- Method signature error when defining commonly used methods.
- The wrong structure label.
- There is no structure literal specifying the field name.
package mainimport ( "fmt")func main() { fmt.Printf(" 哈哈",3.14)}
This example is an obvious error example, the Novice often commit, here we forget to enter the format of the instruction, this editor is not checked out, but if we use it go vet can help us check out this kind of common small errors.
➜ hello go vetmain.go:8: no formatting directive in Printf call
Look, the hint is much more obvious. It go fmt is used in the same way that it accepts a package name as a parameter.
usage: go vet [-n] [-x] [build flags] [packages]
Develop a good habit of checking the code before committing or testing the code to go vet avoid some common problems.
Go test
This command is used for the unit test of Go, it also accepts a package name as a parameter, if not specified, uses the current directory.
go testUnit tests that run must meet the test requirements of go.
- The file name that is written with the unit test must
_test.go end with.
- The test file consists of several test functions.
- These test functions are prefixed with test and receive a
*testing.T parameter of type.
package mainimport "testing"func TestAdd(t *testing.T) { if Add(1,2) == 3 { t.Log("1+2=3") } if Add(1,1) == 3 { t.Error("1+1=3") }}
This is a unit test, saved in a main_test.go file, and unit tested on the functions in the main package Add(a,b int) .
If you want to run this unit test, execute it in the file directory go test .
➜ hello go testPASSok flysnow.org/hello 0.006s
Above is the printout, test pass. For more information on go test the use of commands, see the following commands.
go help test
These, the main introduction of the Go this development tool commonly used commands, familiar with the later can help us to better develop the code. "Go language Combat" in this section to do some introduction, but less, only limited,, go build go clean go fmt , go vet These several commands, here are expanded, but also joined the cross-platform compilation.
Other topics about the Go tool, such as what the package is and so on, can be viewed directly using go help [topic] commands.
Additional help topics: c calling between Go and C buildmode description of build modes filetype file types gopath GOPATH environment variable environment environment variables importpath import path syntax packages description of package lists testflag description of testing flags testfunc description of testing functionsUse "go help [topic]" for more information about that topic.
"Go language Combat" reading notes, not to be continued, welcome attention to the public flysnow_org , the first time to see follow-up notes.