This topic introduces two additional commands for building code:
- The go build command compiles the packages, along with their dependencies, but it doesn't install the results.
- The go install command compiles and installs the packages.
1.From the command line in the hello directory, run the go build command to compile the code into an executable.
$go build
2.From the command line in the hello directory, run the new hello executable to confirm that the code works.
Note that your result might differ depending on whether you changed your greetings.go code after testing it.
Windows:

PS E:\software\golang\goprojects\BMWAWGO> cd hello
PS E:\software\golang\goprojects\BMWAWGO\hello> go build
PS E:\software\golang\goprojects\BMWAWGO\hello> .\hello.exe
map[Darrin:Hail, %v! Well met! Gladys:Hail, %v! Well met! Samantha:Hi, %v. Welcome!]
PS E:\software\golang\goprojects\BMWAWGO\hello>
You've compiled the application into an executable so you can run it. But to run it currently, your prompt needs either to be in the executable's directory, or to specify the executable's path.
Next, you'll install the executable so you can run it without specifying its path.
3.Discover the Go install path, where the go command will install the current package.
You can discover the install path by running the go list command, as in the following example:
PS E:\software\golang\goprojects\BMWAWGO\hello> go list -f '{{.Target}}'
E:\software\golang\go\bin\hello.exe
PS E:\software\golang\goprojects\BMWAWGO\hello>

4.Add the Go install directory to your system's shell path.
That way, you'll be able to run your program's executable without specifying where the executable is.
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$ export PATH=$PATH:/e/software/golang/go/
As an alternative, if you already have a directory like $HOME/bin in your shell path and you'd like to install your Go programs there, you can change the install target by setting the GOBIN variable using the go env command:
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$ go env -w GOBIN=/e/software/golang/go/bin
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
5.Once you've updated the shell path, run the go install command to compile and install the package.
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$ go install
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$
6.Run your application by simply typing its name. To make this interesting, open a new command prompt and run the hello executable name in some other directory.
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$ hello
map[Darrin:Hail, %v! Well met! Gladys:Hail, %v! Well met! Samantha:Hi, %v. Welcome!]
Maxwell Pan@MaxwellPan MINGW64 /e/software/golang/goprojects/BMWAWGO/hello
$

被折叠的 条评论
为什么被折叠?



