Go Language Learning Note 1

Source: Internet
Author: User
Tags alphabetic character sprintf
This is a creation in Article, where the information may have evolved or changed.

1.Go language environment construction and basic knowledge

Official Go Language website (http://golang.org)
Code Package Documentation Web site (http://godoc.org)
Go Language Chinese web (http://studygolang.com)

Go language Development Package download path:
GO1.6.2.LINUX-AMD64 (contains Part1 and part2 two parts, unzip together after downloading)
http://download.csdn.net/download/u012855229/9560392
http://download.csdn.net/download/u012855229/9560394
GO1.6.2.WINDOWS-AMD64 (contains Part1 and part2 two parts, unzip together after downloading)
http://download.csdn.net/download/u012855229/9560395
http://download.csdn.net/download/u012855229/9560400

"Go concurrent Programming" full PDF download path: (including Part1 and part2 two parts, download and unzip together)
http://download.csdn.net/download/u012855229/9560311
http://download.csdn.net/download/u012855229/9560304

"Go concurrency Programming" to use the source code instance download path:
https://github.com/hyper-carrot/goc2p

1.1 Go language configuration environment variables

Under Windows:
goroot={the root directory of your go language}
Appended to the environment variable path;%goroot%\bin
Under Linux:
The Go language official recommends that you copy the Go folder to the/usr/local directory, but you can also copy it to a different directory; Edit the/etc/profile file as follows:
Export Goroot=/usr/local/go
Export path= $PATH: $Goroot/bin
Save the/etc/profile file and use Source/etc/profile to make the configuration effective.
(The specific Linux configuration environment variables can be google,baidu, not mentioned here)

Note: The path connector under Windows is "\" and Linux is "/"

The go language also has two hidden environment variables--goos and Gorach
GOOS represents the target operating system of the program building environment, the value of which can be liunx,windows,freebsd,darwin;
Gorach represents the target computing architecture of the program building environment, which can be either 386,amd64 or arm;
The platform- related directories mentioned later are named by the way of ${goos}_ ${Gorach}.
(such as the path of the go archive file is specified according to the "Platform related directory")

After setting the environment variable, enter go on the command line to see the following message indicating success.
Go is a tool for managing go source code.

Usage:

    go command [arguments]

The commands are:

    build       compile packages and dependencies    clean       remove object files    doc         show documentation for package or symbol    env         print Go environment information    fix         run go tool fix on packages    fmt         run gofmt on package sources    generate    generate Go files by processing source    get         download and install packages and dependencies    install     compile and install packages and dependencies    list        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 packages

Use the "Go help [command]" For more information about a command.

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 functions

Use ' Go help [topic] ' For more information on that topic.

1.2 Work Area
The go code must be in the workspace, and the workspace is actually a directory that corresponds to a specific project, which contains 3 subdirectories of the SRC directory, the pkg directory, and the bin directory.

The
src directory
is used to organize and save the go source file as a code package. The code package here corresponds to sub-directory one by one under SRC. For example, if a source file is declared as belonging to the code package logging, it should be stored in a subdirectory named logging in the SRC directory. Of course, we can also put the go source file directly in the SRC directory, but such a go source file can only be declared as belonging to the main code package. Unless used for ad hoc testing or demonstration, it is generally advisable to put the go source file into a specific code package. The
pkg directory
is used to store the "*.A" archive that is built with the Go Install command, which contains the Go Library source code file. This directory is similar to the PKG feature in the Goroot directory, except that the PKG directory in the workspace is designed to hold the archive file for user code. The process of building and installing a user's source code is typically done in a package, such as when the logging package is compiled and installed, an archive named LOGGING.A is generated and stored in the platform-related directory in the PKG directory of the current workspace. The
Bin directory
is similar to the PKG directory where the executable file generated by the Go command source file is saved after the installation is completed via the Go Install command. Under the Linux operating system, this executable file is usually a file with the same name as the source file. Under the Windows operating system, the name of the executable file is the source file name plus the. exe suffix.

1.3 Gopath
The directory path of the workspace needs to be added to the environment variable Gopath. Otherwise, even in the same workspace (in fact, a directory that is not added to the environment variable Gopath should not be called a workspace), the code cannot be called through an absolute code package path. In real-world development, there are often multiple workspaces, and the directory paths for those workspaces need to be added to Gopath.
There are two workspaces under Linux:
~/go/lib
~/go/goc2p
Modify the/etc/profile file to add the contents of the environment variable Gopath:
Export gopath=$home/go/lib:$home/go/goc2p
Save the/etc/profile file and use the source command to make the configuration effective.

Attention:

  • Gopath do not include the value of the environment variable goroot (that is, the Go installation directory path), the work area of the go language itself and the user's workspace strictly separate;
  • Get the command go get through the code in the Go tool, you can download the source of the specified project to the first workspace we set in the environment variable Gopath, and complete the process of building and installing it.

Under Windows, add the GOPATH environment variable directly in the system variable, where the value is the root directory of your workspace.

1.4 Source Files
Go language source files are divided into 3 categories: Go Library source code files, go command source files and go test source files.

Command source file

A source file that is declared as belonging to the main code package and contains the main function without parameter declarations and result declarations. This type of file can be run independently (using the Go Run command), or it can be converted to an executable file by the go build or go Install command.

All source files in the same code package must have the same name as the code package they belong to. If the command source and library source files are in the same code package, the package will not execute the go build and go install commands correctly. In other words, these source files cannot be compiled and installed. Therefore, the command source files are usually placed separately in a single code package. In general, there is only one boot entry for a program module or software.

There can be multiple command source files in the same code package, which can be run separately by the Go Run command. However, the code package cannot be compiled and installed through the go build and go install commands. Therefore, in general, it is not recommended to put multiple command source files in the same code package.

When there is only one command source file in the code package, execute the Go Build command in the directory where the file is located, you can generate an executable file with the same name as the directory under that directory, and if you use the Go Install command, you can generate the appropriate executable file in the bin directory of the current workspace.

Library source files

A common source file that exists in a code package. Typically, the library source file declares the package name consistent with the name of the code package (directory) it actually belongs to, and the library source file does not contain a parameterless declaration and a no-result declaration of the main function. If the Go install command is executed under the Basic/set directory, the Basic/set package is successfully installed and an archive named Set.a is generated. The directory where the archive is stored is generated by the following rules:

  1. The archive files generated when you install the library source files are stored in the PKG directory of your current workspace.
  2. Depending on the target computer schema being compiled, the archive file is placed in the platform-related directory under the PKG directory. The SET.A on my 64-bit window system is in the PKG\WINDOWS_AMD64 directory.
  3. The relative path to the directory where the archive is stored is consistent with the relative path of the previous-level code package for the installed code package. The first relative path is relative to the platform-relative directory under the PKG directory of the workspace, while the second relative path is relative to the SRC directory of the workspace. If the installed code package does not have a previous level of code package (that is, its parent directory is the SRC directory of work), then its archive will be stored directly in the platform-related directory of the PKG directory of the current workspace. such as the basic Package archive file BASIC.A will always be stored directly in the PKG\WINDOWS_AMD64 directory, and Basic/set package archive set.a is stored in the pkg\ windows_amd64\basic directory.

Test source files

This is a special library file that can run all the test source files under the current code package by executing the Go Test command. There are two sufficient conditions to become a test source file:

  1. The file name needs to end with "_test.go"
  2. The file needs to contain at least one name that is called "Test" at the beginning or "Benchmark" and has a type of "testing." T "or" testing. The function of the parameter of B ". Type "testing. T "or" testing. B "corresponding to the functional test and the basic test required for the structure.

When the Go Test command is executed in a code package, all the test source files in the code package are found and run.

Note : The text file that stores the go code needs to be stored in UTF-8 encoding. If a non-UTF-8 encoded character appears in the source file, go throws a "illegal UTF-8 sequence" error while running, compiling, or installing.

1.5 Code Package
The code package in the Go language is the basic unit for building and Packaging code.

Package Declaration

In the go language, the source file name in the code package can be arbitrary, and these arbitrary name source files must be in the package declaration statement as the first line of code in the file. For example, the SRC directory in the code package Basic/set package of all the source files must first declare that they belong to the Basic/set package:

    set

The package is the keyword used in the Go Language for packet declaration statements. The go language specifies that the package name in the package declaration is the last element of the code package path. As above, the package path for the Basic/set package is Basic/set, and the package name in the package declaration is set. In addition to the command source files, regardless of which package is stored, must be declared to belong to the main package.

Package Import

The import of the code package uses the Code package import path. The Code package import path is the relative path of the code package in the SRC directory of the workspace, such as the absolute path of basic is E:\Go\goc2p\src\basic\set, and E:\Go\goc2p is the workspace directory path contained in the environment variable Gopath. Then its code package import path is Basic/set.

    import basic/set

When you import multiple code packages, you need to enclose them in parentheses, and each code package name is exclusive to one line. When you call a function in the imported code package or use a struct, variable, or constant in it, you need to use the last element of the package path plus "." Specifies the package in which the code resides.

If we have two packages logging and go_lib/logging, and have the same method Newsimplelogger (), and there is a source file that needs to be imported into both packages:

    import (        "logging"        "go_lib/logging"    )

Then this code logging. Newsimplelogger () can cause conflicts, and the go language cannot know logging. Which package is represented. So, in the go language, if you import multiple code packages in the same source file, the last element of the code package path cannot be duplicated.

If you use this code package to import code, the Go language throws "logging redeclared as Imported package name" error when compiling the code. If you do need to import, when there are such repetitions, we can differentiate them by individual names:

    import (        "logging"        "go_lib/logging"    )

Call the code in the package:

    var logger la.Logger = la.NewSimpleLogger()

There is no need to alias each code package that causes the conflict, as long as you can differentiate between them.

If we want to call a program that relies on a package directly, we can use the "." To replace aliases.

    import (        "logging"        "go_lib/logging"    )

In the current source file, code calls can be made directly:

    var logger Logger = NewSimpleLogger()

The go language collectively refers to variables, constants, functions, structs, and interfaces as program entities, and names them collectively as identifiers. An identifier can be an alphabetic character, a number, and an underscore "_" that any Unicode encoding can represent, and the first letter cannot be a number or an underscore.

The case of the first letter of the identifier controls the access rights of the corresponding program entity. If the first letter of the identifier is capitalized, then its corresponding program entity can be accessed by code outside of this code package, or it can be called exportable. Otherwise, the corresponding program entity can only be accessed by the code within the package. Of course, the following two additional conditions are required:

  1. The program entity must be non-local. A local program entity is defined inside a function or struct.
  2. The directory where the code package resides must be included in the workspace directory in the environment variable Gopath.

If there is a function called Getsimplelogger in the code package logging, we can see from the name of the function that this function cannot be called by the outside of the package code.

If we just want to initialize a code package without needing any code from that code in the current source file, you can use "_" instead of the alias

    import (        _ “logging”    )

Package initialization

In the go language, you can have specialized functions that are responsible for the initialization of the code package. This function requires a parameterless declaration and a result declaration, and the name must be init, as follows:

    init() {        println("Initialize")    }

The go language analyzes the dependencies of the entire program before the program actually executes and initializes the associated code package. That is, all the code-package initialization functions are completed before the main function (the entry function in the command source file) and are executed only once. Also, the initialization of all global variables in the current code package is done before the code package initialization function executes. This avoids the problem of overwriting a variable with a value that is given in the declaration of the variable after the code-package initialization function has been assigned a value.

Here is an example of "go concurrency programming" to help understand the above package initialization, as follows:

     PackageMain//Command source files must be declared here that they belong to the main package    Import(//introduced the code package FMT and runtime        "FMT"        "Runtime")funcInit () {//Package initialization functionFmt. Printf ("Map:%v\n", m)//format and re-print first        //By calling the runtime package's code to get the operating system running on the current machine and computing the schema        ///Then string format and assign value to variable info via the sprintf method of the FMT packageinfo = fmt. Sprintf ("OS:%s, Arch:%s", runtime. GOOS, runtime. Goarch)}//non-local variable, map type, and initialized    varMMap[int]string=Map[int]string{1:"A",2:"B",3:"C"}varInfostring //non-local variable, string type, uninitialized    funcMain () {//Command source file must have entry functionFmt. PRINTLN (Info)//Print variable info}

The named source file is named Initpkg_demo.go and saved to the Basic/pkginit package in the workspace. As the result of my native run:

In the same code package, you can have multiple code-package initialization functions, and even each source code file within a package can define multiple code-package initialization functions. The go language compiler does not guarantee that multiple code packages in the same code package initialize the order in which the functions are executed. You might consider using channel (a member of the Go Language concurrency programming model) to control if you want to perform in a specific order.

The Go language recognizes two special code package names--all and Std. All represents all the code packages in all the workspaces contained in the environment variable Gopath, while STD represents all the code packages in the Go Language standard library.

Overview of STANDARD commands

  • Build compiles a given code package or go Language source file and its dependent package
  • Clean clears directories and files left after performing other go commands
  • The doc executes the Godoc command to print the specified code package.
  • ENV Print Go locale information
  • Fix executes the Go tool fix command to fix outdated syntax and code calls contained in the source file for a given code package
  • FMT executes the GOFMT command to format the source file in the Godin code package.
  • Generate generate Go files by processing source
  • Get download and install a given code package and its dependent packages
  • Install to compile and install a given code package and its dependent packages
  • List displays information for a given code package
  • Run compiles and runs the given command source file
  • Test tests the given code package
  • Tool to run the Go language
  • Version displays information about the currently installed go language
  • Vet Run Go tool vet on packages

When executing these commands, you can customize the execution of the command by attaching some additional tags, which can be considered special parameters of the command, which can be added to the middle of the command name and the real parameters of the command, as follows:

  • -A forcibly re-constructs all the involved go language code packages, including the code packages in the Go Language standard library, even though they are already up to date.
  • The-N mission order prints only all commands used during execution, rather than actually executing them.
  • -V Prints the name of the Go language code package involved in the execution of the command. These packages typically include our own given target code package, and sometimes include code packages that the code package relies on directly or indirectly.
  • -work prints the name of the temporary working directory that is generated and used when the command executes, and does not delete the command when it is completed.
  • -X prints out all the commands that were used during the command execution.

A special tool for the Go language, as follows:

  • Fix can modify the old version code in all the Go Language source files for the given code package to the new version. It is the tool that we will use when we upgrade the Go language version.
  • Vet is a simple tool to check for static errors in the Go Language source code. You can use it to detect some common go language coding errors.
  • Pprof is used to interactively access some performance profiles. The command will parse the given profile and provide high-readability output information as required. This tool can parse profiles including CPU profiles, memory profiles, and program blocking profiles. These profiles containing the go language runtime information can be generated through the standard library code package runtime and RUNTIME/PPROF programs.
  • CGO is used to help the Go language code use the C language code base, and the Go language code can be referenced by the C language code.

Finally, I attach the "Go concurrent programming Combat" author it to GitHub's Go Command tutorial, which involves the detailed use of GO commands and tools:
Https://github.com/hyper-carrot/go_command_tutorial

Go language learning on the first day, after a continuous update ...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.