This is a creation in Article, where the information may have evolved or changed.
Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy-to-write programs that get the most out of multicore and networked machines, while Its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet have the convenience of garbage collection and the power of Run-time reflection. It's a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.
– excerpted from the official Go language site
The most profound love for a programming language is the recognition of the design concept of the programming language, and the go language is a programming language that makes me feel so after C language.
When I first heard the language, I frowned: how did I get such a name! Most programming languages are named after nouns or names (such as C, Java, Python, Ruby, Haskell, Ada, etc.), and the language uses a verb go that is used very frequently in daily life, which seems to be a bit too popular. I do not know why, this name always reminds me of the former Chinese countryside to children often up a few names: two dogs, Niuwa and other ^_^. Moreover, there have been many IT products with go as the name (for example, ThoughtWorks Company's agile management tools also called go).
But with a deeper understanding of the language, the name is no longer a problem. The go language has a strong appeal to me as a C programmer for the following reasons:
* Go maintains the concept of same strain with C language: short, dedicated to become a system programming language, concise and familiar with the C language family syntax, static compiler language, retain the pointer, run efficiently;
* Go filled in the C language with a number of the birth of the "pit";
* Go improves compilation speed, unifies the source organization, constructs the specification and the Code standard, lets the programmer focus on the problem domain more;
* Go improves concurrency model and natively supports multi-core platforms at the language level;
* The go language has a high starting point and is compatible with existing mainstream programming paradigms (such as OO, etc.) with innovative design and very small costs.
So some people call go the C language of the 21st century, I think not too. Starting with this article, I will go into the world of Go language with everyone.
First, install Go
Go Language official station (from the domestic visit is very unstable, when can not, why you understand) The go installation has a more detailed description. If you are using Linux, Mac OS, or Windows, you should be able to complete the go installation smoothly. Go released the first stable version of Go 1 early this year, and the latest version is 1.0.2, which can be downloaded from the Go project on Google Code. My environment for Ubuntu 10.04 32-bit, after downloading go1.0.2.linux-386.tar.gz, unzip to/usr/local/go below:
$ ls/usr/local/go
Api/bin/doc/include/license Patents README Src/version
AUTHORS CONTRIBUTORS favicon.ico lib/misc/pkg/robots.txt test/
Then add the/usr/local/go/bin to your PATH environment variable and you can execute the GO program in any directory:
$ go version
Go version go1.0.2
If you get the above output, you can conclude that your go installation is successful!
Second, the first Go program –hello, go!
We set up a working directory Go-examples to write the Go program with an absolute path of/home/tonybai/go-examples. Well, start writing our first go program.
We create a file hellogo.go under Go-examples, which reads as follows:
Package Main
Import (
"FMT"
)
Func Main () {
Fmt. Printf ("Hello, go!\n")
}
Let's compile the source file and execute the resulting executable file:
$ go Build hellogo.go
$ ls
hellogo* Hellogo.go
$ hellogo
Hello, go!.
With Go build plus the Go source file name to compile, we can get an executable file, by default the name of the file is the name of the source file removed. go suffix. Of course we can also use the-o option to specify a different name:
$ go build-o myfirstgo hellogo.go
$ ls
myfirstgo* Hellogo.go
If we execute the go build command directly in the Go-examples directory, followed by a file name, we will get an executable with the same name as the directory name:
$ go Build
$ ls
Go-examples* Hellogo.go
Iii. Program Entry points (entry point) and packages (package)
Go maintains the same style as the C-family language: The go source of the target executable must have a function called Main, which is the entry point for the executable. In addition, go adds a constraint: The main function as the entry point must be in the package named Main. As in the Hellogo.go source file above, the first line of the source code declares that the package that the file belongs to is main.
Go removes the concept of header files, and draws on the source organization of the package used by many mainstream languages. The package is a logical concept, with no one by one correspondence to the file. If more than one source file declares itself to belong to a package named Foo at the beginning, the code in these source files is logically subordinate to package Foo (these files are preferably in the same directory, at least the current go version cannot support the source files belonging to the same package in different directories).
We see Hellogo.go import a package named FMT and use the printf function within the package to output "Hello, go!". Intuition tells us that the FMT package appears to be a package in a standard library. Yes, the FMT package provides formatted text output and a related function to read formatted input, similar to printf or scanf in C. After we have imported the FMT package into our source file through the import statement, we can use the FMT package export function function (such as Printf).
In C, we use static to identify the local function or the global function. In go, the function in the package can be called externally, to see if the first parent of the function name is uppercase. This is a Go language curing convention: The first-uppercase function is considered an exported function, can be called by code outside the package, and a function that starts with a lowercase letter can only be used within the package. In the example you also see the printf function of the FMT package whose first parent is capitalized.
Iv. Gopath
We transformed the hellogo.go above and split it into two files: Main.go and Hello.go.
/* Hello.go */
Package Hello
Import "FMT"
Func Hello (who string) {
Fmt. Printf ("Hello,%s!\n", WHO)
}
/* Main.go */
Package Main
Import (
"Hello"
)
Func Main () {
Hello. Hello ("go!")
}
To compile main.go with go build, the results are as follows:
$ go Build main.go
Main.go:4:2:import "Hello": Cannot find Package
The compiler actually suggested that the package hello could not be found, while the package hello.go was clearly defined in the package. What's going on here? The way go compiler search package is different from our conventional understanding, go has a set of conventions in this respect, which involves an important environment variable: Gopath. We can use Go help Gopath to see the manual about Gopath.
The package search order for Go compiler is like this, as an example of searching for the Hello package:
* First, go compiler in the Go install directory (Goroot, here is/usr/local/go) to find out if there is src/pkg/hello related package source;
* If Export gopath=path1:paht2, go compiler will look for the presence of Path1/src/hello, Path2/src/hello ; the PATH1 and PATH2 configured in Gopath are called workplace;
* If the Hello package cannot be found in any of the above locations, an error is indicated.
In this case, we have not set the GOPATH environment variable, nor have we established a path like Path1/src/hello, so go compiler obviously can't find the Hello package. Let's set up the Gopath variable and create the relevant directory:
$ Export Gopath=/home/tonybai/go-examples
$ mkdir Src/hello
$ mv Hello.go Src/hello
$ go Build main.go
$ ls
main* Main.go src/
$ main
Hello, go!.
Five, Go install
We moved main.go to Src/main, so this demo project seems more reasonable, all the source code is under SRC:
$CD SRC
$ ls
hello/main/
Go provides the install command, which, in contrast to the build command, installs the executable file or library file into the agreed directory after compiling the source. Let's take the main directory as an example:
$ CD Main
$ go Install
After the install command was executed, we found that there was no change in the main directory, and the main executable that was generated at the original build was missing. Don't worry, the previous said go install also has its own agreement:
* Go install (under Src/dir) the compiled executable file is named after its directory name (DIR)
* Go install installs the executable file in the bin directory with the SRC peer, and the bin directory is created automatically by go install
* Go install compiles the various package that the executable depends on and places it in the PKG directory at the same level as the SRC
Now let's take a look at the bin directory:
$ ls/home/tonybai/go-examples
bin/src/pkg/
$ ls Bin
main*
A bin directory does appear, and the program you just compiled is main under the bin.
Hello.go is not executable after compiling the main, and since main relies on the Hello package, the Hello is also associated with the compilation. This is the same as the result of executing the install separately in the Hello directory, let's try:
$ cd Hello
$ go Install
$ ls/home/tonybai/go-examples
bin/pkg/src/
In our workspace (go-examples directory) There is a pkg directory, the pkg directory is a subdirectory named Linux_386, which has a file: Hello.a. This is the result of our install. The Hello.go is compiled into HELLO.A and installed into the pkg/linux_386 directory.
. A This suffix reminds us of a static shared library, but here. A is a unique file format for go, and is not compatible with traditional static shared libraries. But the designer of the Go language uses this suffix to look like this. A file also assumes the role of the "Static shared library" in the Go language. We might as well try to see if this hello.a can be treated as a "static shared library" by Go compiler. We remove the Hello directory from src and then execute go build in the main directory:
$ go Build
Main.go:4:2:import "Hello": Cannot find Package
Go compiler hint cannot find hello this package, the current version of the go compiler seems to ignore the. a file under Pkg. http://code.google.com/p/go/issues/detail?id=2775 This issue also confirms this, but subsequent go versions are likely to support link. a files. After all, we in the use of third-party package, it is likely to not get its source code, and in each project to save a third-party packages of the source code is also very detrimental to the project source of late maintenance.
VI. Run the Go source code like a script
Go has a high compiler efficiency, which is due to the designer's attention to this goal and the details of the design process of the control, of course, this is not the topic of concern in this article. It is because Go has a fast compilation that we can use it as if it were running a scripting language.
Now go provides the Run command to run the source file directly. Like what:
$ go Run main.go
Hello, go!.
Go run is actually a command that will compile the source code and run the compiled binaries together. However, the go source file is not yet supported as Shebang Script, because go compiler does not recognize the #! symbol, the following source code file will run error:
#! /usr/local/go/bin/go Run
Package Main
Import (
"Hello"
)
Func Main () {
Hello. Hello ("go!")
}
$ go Run main.go
Package:
Main.go:1:1:illegal character u+0023 ' # '
But we can use some third-party tools to run Shebang Go scripts, such as Gorun.
Seven, test go program
As mentioned earlier, go has a higher starting point, so it provides itself with a lightweight unit Test framework package and commands to run the test set.
We use an example to illustrate how to write the test code for a package and how to run the test. We set up another directory under GO-EXAMPLES/SRC the code for the MyMath package under Mymath,mymath directory is as follows:
/* Mymath.go */
Package MyMath
Func myadd (i int, j int) int {
return i + j
}
To test the MyMath package, we need to create the Mymath_test.go file in the same directory, where the test code for the Myadd function is as follows:
/* Mymath_test.go */
Package MyMath
Import "Testing"
Func testmyadd (t *testing. T) {
A, B: = 4, 2
If x: = Myadd (A, b); X! = 6 {
T.errorf ("Myadd (%d,%d) =%d, want%d", a, B, X, 6)
}
}
In this file we import the standard unit test package-testing that go provides, and each test method has test as the prefix. Now let's run this test and run the Go Test command in the MyMath directory:
$ go Test
PASS
OK MyMath 0.007s
If the use case goes wrong, we can see the following prompt:
$go Test
-fail:testmyadd (0.00 seconds)
Mymath_test.go:8: Myadd (4, 2) = 6, want 6
FAIL
Exit Status 1
FAIL MyMath 0.007s
As can be seen, Go test also has its own some conventions: the test source file name must be _test.go as the end of the test code and the code in the same package, test code to import the testing package, test function to be tested as a prefix, and the function signature of the test function must be this: Func testxxx (t *testing. T).
The benefits of language-to-test support are consistent, avoiding the inconvenience of reading, communicating and maintaining with different test frameworks.
Viii. Project Source organization
With the source code, with the understanding of the principle of compiling, with the support of the test framework, we can plan the project source organization. But many of the conventions of go have basically limited us to the following structure:
proj1/
bin/
Myapp1*
pkg/
linux_386/
lib1.a
lib2.a
src/
lib1/
Lib1.go
Lib1_test.go
lib2/
Lib2.go
Lib2_test.go
... ...
myapp1/
Main.go # Main package source
Main_test.go # test Source
proj2/
bin/
myapp2*
pkg/
linux_386/
lib3.a
lib4.a
src/
lib3/
Lib3.go
Lib3_test.go
lib4/
Lib4.go
Lib4_test.go
... ...
myapp2/
Main.go # Main package source
Main_test.go # test Source
Based on the above structure, we can set the Gopath to Proj1_path:proj2_path.
Nine, code style (coding style)
Go programmers can no longer dwell on what style of code to use, because go has made the code style strict conventions, once violated, compiler directly give error. Go also provides the FMT command to assist go programmers to format the source files as standard.
From the example above we can see that the main features of Go are:
* The left curly brace ' {' must be on the same line as the function name or if statement
Func Foo {
}
* There is no need to explicitly use semicolons, separate statements (unless you write multiple statements on one line), because compiler will add semicolons to the appropriate location for everyone.
I, J: = 2, 3
Myadd (i, J)
If x: = Myadd (A, b); X! = 6 {
... ...
}
* If, for, and so on, the expression does not have to be enclosed in parentheses
if x! = 5 {
... ...
}
X. Viewing documents
Go's full-volume documentation is published almost with the go installation package. After you install go, execute the godoc–http=: Port number to start the doc server. Open the browser and enter the http://localhost: port number to see almost the same document page as the Go official station.
Xi. Reference Books
After all, go is a new generation of language, its own immature and perfect, the data is also less. Here are two books on the market that are better and have been updated to go 1:
* Mark Summerfield's "Programming in go:creating applications for the 21st century"
* Ivo Balbaert's "The Go–a thorough Introduction to the Go programming Language"