Go locale installation and program structure
1. Go environment installation
Go installation package download address is:
https://golang.org/dl/
https://golang.google.cn/dl/
1.1 Installation under Windows
Under Windows, you can use the installation package with the suffix .msi
to install. The installation package I downloaded here is go1.18.4.windows-amd64.msi
, double
Click the installation package, configure the installation path, and then click Next to install.
The directory structure after the installation is complete:
The structure of this directory follows the GOPATH rules, and the meaning of each folder in the directory is shown in the following table:
api
: Differences in API changes for each version
bin
: Compiler (go), documentation tool (godoc), formatting tool (gofmt) compiled from the source package
doc
: Go documentation in English
lib
: Some library files referenced
misc
: files for miscellaneous purposes, such as Android platform compilation, git commit hooks, etc.
pkg
: Platform compiled intermediate files
src
: the source code of the standard library
test
: test case
After the installation is complete, use go version
to view the version:
# Enter cmd to execute the following command $ go version go version go1.18.4 windows/amd64
1.2 Installation under Linux
The following describes how to use the source code to install under the Linux system:
1. Download the binary package: go1.18.4.linux-amd64.tar.gz
.
2. Upload the downloaded binary package to the /home/zhangshixing
directory and decompress it.
$ cd /home/zhangshixing # The directory after decompression is go $ tar -xvf go1.18.4.linux-amd64.tar.gz
3. Add the /home/zhangshixing/go/bin
directory to the PATH environment variable:
$ export PATH=$PATH:/home/zhangshixing/go/bin
The above can only temporarily add PATH, and it will be gone after closing the terminal and logging in next time.
We can edit ~/.bash_profile
or /etc/profile
, and add the following command to the end of the file, so that it will take effect permanently:
$ vim /etc/profile # Add the following content export PATH=$PATH:/home/zhangshixing/go/bin
After adding, you need to execute:
$ source ~/.bash_profile or $ source /etc/profile
After the installation is complete, use go version
to view the version:
$ go version go version go1.18.4 linux/amd64
1.3 Package management environment configuration
The environment variables that need to be configured for go development are as follows:
# Take the configuration under Linux as an example, the configuration under Windows is the same, but the configuration method is different # Configure the following variables in ~/.bash_profile or /etc/profile for permanent effect export PATH=$PATH:/home/zhangshixing/go/bin export GOROOT="/home/zhangshixing/go" export GOPATH="/home/zhangshixing/go_work_space" export GOBIN="/home/zhangshixing/go/bin" export GO111MODULE=on export GOPROXY=https://goproxy.cn,direct export GOMODCACHE="/home/zhangshixing/go_work_space/pkg/mod"
Description of the four variables GOPATH
, PATH
, GOROOT
, GOBIN
:
GOROOT
is the installation path of go;GOPATH
is the working directory of go;PATH
is the bin directory under the go installation path.GOBIN
is the bin directory under the go installation path.
1.4 Description of system environment variable configuration file
# bashrc is valid for all users of the system, profile is valid for the current user vim ~/.bashrc vim ~/profile
# Update environment variables and take effect in time source ~/.bashrc source ~/profile
1.5 Working directory
The directory specified by the $GOPATH
environment variable is called the Go working directory, and $GOPATH
can be configured as multiple directories.
The working directory has the same directory structure with three subdirectories:
$GOPATH/---| |-----src |-----pkg |-----bin
src is the directory where the source code of the project is located. Generally, the first-level directory under src is the project root directory. The project root directory generally adopts the company’s domain name + project name or
The format of the user name, such as the project source code organization form on GitHub:
# The following are the project root directories $GOPATH/src/github.com/github/ $GOPATH/src/github.com/golang/
The root directory of the project is the directory of each project in the project. The source code files and the source code of various packages can be stored in the project directory. This is a recommended code organization
form. Give a specific example: $GOPATH/src/github.com/github/gh-ost
, $GOPATH/src/github.com/github/
GitHub
is the root directory of the project, gh-ost
is the specific project directory, and gh-ost
is the source code and package of the project.
The $GOPATH
environment variable can configure multiple directories. When using go
to download a third-party package, the package will be downloaded to the first $GOPATH
directory
On the surface, many people like to configure two directories in GOPATH
, the first directory is dedicated to downloading third-party packages, and the second directory is used for internal engineering projects
This is also a solution to avoid mutual interference between external packages and its own project code. But the official recommendation is to use only one directory
GOPATH
, combined with the official package management tool to manage.
1.6 Cross compilation
After version 1.5, the Go compilation tool is completely rewritten in Go language. The Go compiler has a built-in cross-compilation function. You only need to set GOOS
and GOARCH
Variables can then be easily cross-compiled.
Go cross-compilation involves the setting of several environment variables: GOARCH
, GOOS
and CGO_ENABLED
.
GOARCH
: Compile the hardware architecture of the target platform (amd64, 386, arm, ppc64, etc.).
GOOS
: Compile the operating system on the target platform (darwin, freebsd, linux, windows).
CGO_ENABLED
: indicates whether to enable CGO, 1 means enable, 0 means disable. Since CGO cannot support cross-compilation, it needs to be disabled.
Let’s look at a specific example:
package main import ( "fmt" "runtime" ) func main() {<!-- --> fmt.Printf("OS:%s\\ Architecture:%s\\ ", runtime.GOOS, runtime.GOARCH) }
Compile Linux and Windows 64-bit executable programs under Mac:
export CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go export CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go
Compile Mac and Windows 64-bit executable programs under Linux
export CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go export CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go
Compile Mac and Linux 64-bit executable programs under Windows
SET CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go SET CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go
Other platforms or 32-bit systems are similar, so I won’t repeat them here.
1.7 Go project initialization
Some Go standard libraries strongly depend on the go mod command.
(1), go mod init module_name
Initializes a new module in the current directory, generating a go.mod file.
(2), go mod tidy
Missing dependencies are added, or unused dependencies are removed. In general, we recommend that after creating a project, or after adding new dependencies to
After that, execute the command.
2. Go language structure
Before we start learning the fundamental building blocks of the Go programming language, let’s understand the structure of the simplest program in Go.
2.1 Go Hello World example
The basic composition of the Go language has the following parts:
- package declaration
- import package
- function
- variable
- statement & expression
- note
Hello World
code:
package main import "fmt" func main() {<!-- --> /* This is my first simple program */ fmt.Println("Hello, World!") }
Let’s look at the various parts of the above program:
1. The first line of code
package main
defines the package name, you must specify which package this file belongs to in the first line of the source file that is not a comment.The package name is generally the same as the directory to which it belongs.
package main
represents a stand-alone executable program, and every Go application contains aA package named
main
.
2. The next line
import "fmt"
tells the Go compiler that this program needs to use the fmt package (function, or other elements), and the fmt package implementsFunctions for formatting IO (input/output).
3. The next line
func main()
is the function that the program starts to execute. Themain
function must be included in every executable program. Generally,It is said that it is the first function to be executed after startup (if there is a
init()
function, it will be executed first).
4. The next line
/*...*/
is a comment, which will be ignored when the program is executed. Single-line comments are the most common form of comments, you can use them anywhereUse single-line comments starting with
//
. Multi-line comments are also called block comments, which start with /* and end with */, and cannot be nested. Multi-line commentsComments are generally used for package documentation descriptions or to annotate code snippets into blocks.
5. The next line
fmt.Println(...)
can output the string to the console, and automatically add a newline character\\
at the end. use
fmt.Print("hello, world\\
can get the same result. The two functions
")Println
also support the use of variables,Such as:
fmt.Println(arr)
. If not specified, they output the variablearr
to the console in the default print format.
6. When the identifier (including constants, variables, types, function names, structure fields, etc.) starts with a capital letter, such as:
Group1
, thenObjects using this form of identifier can be used by code in external packages (client programs need to import this package first), which is called importing.
(like
public
in object-oriented languages); identifiers that start with a lowercase letter are not visible outside the package, but they are used throughoutThe internals of the package are visible and usable (like
protected
in object-oriented languages).
2.2 Executing Go programs
Let’s write Go code and execute it:
$ go run helloworld.go Hello, World!
We can also use the go build
command to generate binaries:
$ go build hello.go # Under Linux, the helloworld executable file will be generated # Generate helloworld.exe executable file under Windows # Can be executed individually like an executable
It should be noted that {
cannot be placed on a single line, so the following code will generate an error when running:
package main import "fmt" func main() {<!-- --> fmt.Println("Hello, World!") }
2.3 About packages
golang uses the package package
to manage and define modules, and you can use the import
keyword to import and use.
-
If you import the package that comes with go, it will go to the installation directory
$GOROOT/src
to load according to the package path, such as the fmt package -
If it is a package installed or customized by our go get, it will be loaded under
$GOPATH/src
The storage location of the package is based on $GOPATH/src
as the root directory, and then flexibly organized according to the directory, and the package name must be the same as the last level directory name
Sincerely. For example, if we customize the baz
package, the storage location of the package module is the source code of the $GOPATH/src/foo/bar/baz
, baz
package are stored in this directory
Recorded, foo/bar/baz
is imported as a package path.
We need to standardly define the source code package in the baz package as baz
, and then define a package that can be imported and loaded.
Regarding the package, the following points are obtained according to local tests:
-
The file name is not directly related to the package name, and it is not necessary to set the file name and the package name to be the same.
-
The folder name is not directly related to the package name and does not need to be the same.
-
Files in the same folder can only have one package name, otherwise an error will be reported when compiling.
Code of package demo
:
# directory structure [root@zsx src]# tree package_demo/ package_demo/ ├── go.mod ├── math_func │ ├── math1.go │ └── math2.go └── math_main └── test.go
package main import ( "fmt" "proj/math_func" ) func main(){<!-- --> \t// 2 fmt.Println(mathclass.Add(1,1)) // 0 fmt.Println(mathclass.Sub(1,1)) }
package mathclass func Add(x, y int) int {<!-- --> return x + y }
package mathclass func Sub(x, y int) int {<!-- --> return x - y }
The Go language uses packages to organize source code and implement namespace management. Any source code file must belong to some package. The first line of the source code file
A valid code must be a package pacakgeName
statement, which declares the package it is in.
2.3.1 Basic concepts
Packages in the Go language use the organization form of the directory tree. Generally, the name of the package is the name of the directory where the source file is located, although Go does not enforce that the package name must be the same as
The directory where it is located has the same name, but it is recommended that the package name and the directory where it is located have the same name, so that the structure is clearer. Packages can be defined in deep directories, package definitions
The directory path is not included, but the package reference is generally a full path reference. For example, define a package c under $GOPATH/src/a/b/
, in the source of package c
The code only needs to be declared as package c
instead of package a/b/c
, but when import
package c, you need to bring upper path
import a/b/c
. There are two forms of package references, which will be described in detail later.
Package idioms:
-
Package names are generally lowercase, use a short name.
-
The package name is generally the same as the directory where it is located.
-
It is generally placed in the company’s domain name directory, which can ensure the uniqueness of the package name and facilitate code sharing. For example, the package of a personal GitHub project is generally placed
In the
$GOPATH/src/github.com/userName/projectName
directory.
2.3.2 Package Reference
The source code of the standard package is located under $GOROOT/src /
, and the standard package can be directly cited. The source code of custom packages and third-party packages must be placed in
$GOPATH/src
directory can be referenced.
Package reference path:
There are two ways to write the reference path of the package, one is the full path, and the other is the relative path.
Full path reference
The absolute path of the package is the full path of the bread source code after GOROOT/src
or $GOPATH/src
, such as the following package reference:
import "lab/test" import "database/sql/driver" import "database/sql"
The test package is a custom package, and its source code is located in the $GOPATH/src/lab/test
directory; the source codes of the sql and driver packages are located in
$GOROOT/src/database/sql
and $GOROOT/src/database/sql/driver
.
Relative path reference
Relative paths can only be used to refer to packages under $GOPATH, and references to standard packages can only use full path references. For example, the following two packages: the path of package a is
$GOPATH/src/lab/a
, the source path of package b is $GOPATH/src/lab/b
, assuming that b refers to package a, you can use a relative path Referrer
Mode. Examples are as follows:
// relative path reference import "../a"
// full path reference import "lab/a"
Package Reference Format
There are four reference formats for package references. For the convenience of description, we take the fmt standard library as an example for illustration.
- Standard citations are as follows
import "fmt"
At this time, you can use fmt. as a prefix to refer to the exportable elements in the package, which is a common way.
- The alias reference method is as follows
import F "fmt"
At this time, it is equivalent to giving the package fmt an alias F, and using F. instead of the standard fmt as a prefix to refer to the exportable elements in the fmt package.
- The omission method is as follows
import . "fmt"
At this time, it is equivalent to directly merging the namespace of the package fmt into the namespace of the current program, and the exportable elements in the fmt package can be used without the prefix
fmt., direct quote. Examples are as follows:
package main import . "fmt" func main() {<!-- --> // No need to add pre-stage fmt. Println("hello, world!") }
- Execute only the package initialization init function
If a package is referenced using the standard format, but the package is not used in the code, the compiler will report an error. If there is an init initialization function in the package, pass
import_“packageName” refers to the package in this way, only the initialization function of the package is executed, even if the package does not have an init initialization function, it will not
Causes a compiler error. Examples are as follows:
import_"fmt"
A package can have multiple init functions, and package loading will execute all init functions, but the order of execution is not guaranteed, so it is not recommended to use them in one package
Put multiple init functions, and put the logic that needs to be initialized into the init function.
2.4 Go language common commands
command | description |
---|---|
go env | Used to print the environment information of Go language |
go run | The command can compile and run the command source file |
go get | You can download or update the specified code package and its dependent packages from the Internet according to the requirements and actual situation, and compile and install them |
go build | The command is used to compile the source code files or code packages we specify and their dependent packages |
go install | It is used to compile and install the specified code packages and their dependent packages |
go clean | The command will delete the generated when executing other commands Some files and directories of |
go doc | The command can print the documentation attached to the Go language program entity. We can view its documentation by using the identifier of the program entity as the parameter of the command. |
go test | The command is used for the Go language The written program is tested |
go list | The function of the command is to list the information of the specified code package |
go fix | will correct the old version code in all Go language source code files of the specified code package to the new version code |
go vet | is a simple tool for checking static errors in Go language source code |
go tool pprof | command to interactively |
go tool cgo | This tool allows us to create Go language source files that can call C language code |