This is a creation in Article, where the information may have evolved or changed.
"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.
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.
1234567891011121314151617181920212223242526272829303132333435363738394041 |
➜~ GoGo is a tool forManaging GoSourceCode. Usage:goCommand[Arguments] The commands Are:build compile packages and Dependenciesclean remove Object Filesdoc show Documentatio N forPackage or SymbolenvPrintGo environment informationbug Start a bug reportfix run Go tool fix on Packagesfmt run GOFMT on PA Ckage sourcesgenerate generate Go files by processingSourceGet download and install packages and Dependenciesinstall compile and install packages and dependencieslist List Packagesrun compile and run Go programTest TestPackagestool run specified go toolversionPrintGo versionvet run Go tool vet on Packagesuse"Go help [command]" forMore information about a command. Additional HelpTopics:c calling between Go and Cbuildmode description of build Modesfiletype file Typesgopath Gopath Environment variableenvironment Environment Variablesimportpath Import path syntaxpackages description of package list Stestflag Description of testing Flagstestfunc description of testingfunctionsUse"Go help [topic]" forMore 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.
1 |
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:
12345 |
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.
1 |
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.
1 |
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.
12345678 |
➜ ~ 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:
1 |
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 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.
1 |
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 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.
1234567891011121314151617 |
➜~ Go HelpRunusage:go run [build flags] [-exec Xprog] gofiles ... [Arguments ...] Run compiles and runs the main package comprising the named GoSourceFiles. A GoSourceFile is defined to be a file endingincha 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 _execCan is Foundon the current search path,' Go run 'Invokes the binary using that program, forExample' 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:
1234567891011 |
Package mainimport ("FMT""OS")funcmain() {fmt. PRINTLN ("input parameter is:", OS.) args[1])} |
Open Terminal, enter the following command to execute:
Then we can see the output:
1 |
The input parameters are: 12 |
Go env
As we said earlier go build , we used the go env command to view our current go environment information.
123456789 |
➜ 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 are 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.
12345 |
➜ Hello go help installusage:go install [build flags] [Packages]install compiles and installs the packages named by T He 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.
1 |
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.
1 |
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 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.
12 |
func Main () {fmt. PRINTLN ("input parameter is:", OS.) args[1])} |
For example, the above code, after we do go fmt the formatting, will become the following:
123 |
func Main () {fmt. PRINTLN ("input parameter is:", 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.
1234567891011 |
➜ Hello gofmt-h usage:gofmt [flags] [path ...] -cpuprofile string Write CPU profile to the This file- ddisplay diffs instead of rewriting files -e< /c9>report all errors (not just the first ten on different lines)- lList files whose formatting differs fro M gofmt' s -r string rewrite rule (e.g, ' A[b:len (a)], A[b:]') -ssimplify Code -wwrite 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.
123456789 |
Package mainimport ("FMT")funcmain() {fmt. Printf ("haha",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.
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.
1 |
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.
12345678910111213 |
Package mainimport"testing"functestadd(t *testing. T) {if Add (1,23 {t.Log ("1+2=3")}if Add ( 1,13 {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 .
123 |
➜ Testpassok flysnow.org/hello0.006s |
Above is the printout, test pass. For more information on go test the use of commands, see the following commands.
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.
12345678910111213 |
help Topics:c calling between Go and Cbuildmode description of build modesfiletype file Typesgopath Gopath Environment variableenvironment Environment Variablesimportpath Import Path Syntaxpackages Description of package Liststestflag description of testing Flagstestfunc functions ' Go help [topic] ' For more information on that topic. |
"Go language Combat" reading notes, not to be continued, welcome to sweep code attention flysnow_org to the public, the first time to see follow-up notes.