Start learning Go

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

This document is translated from Dr.dobb's "Getting going with Go".

This is the first part of a five-week tutorial on Google's new system native language, which will show you how to build the Go language development environment and build your program, and then take you through some code examples to focus on some interesting features of the language.

This tutorial series will be published for five consecutive weeks. In today's section, go language expert Mark Summerfield will explain how to build a go language development environment that provides two go language paradigms and gives deep parsing. These sample programs give you a partial demonstration of some of the key features of the go language as well as packages. The next few weeks will showcase the rest of the key features, and specifically for C, C + + and Java programmers to delve into the features unique to the go language.

As explained in this week's editor's article, the Go language has many unique features, so it may be called the C language of the 21st century. And given that Ken Thompson is also one of the designers of the language, the two languages do have a common ancestor.

Begin

Go is a compiled language, not an interpreted type. Go compiles very quickly-even faster than other similar languages-well-known such as C and C + +.

The standard go language compiler is called a GC, and its associated toolchain includes 5g, 6g, and 8g for compilation, 5l, 6l, and 8l for linking, and godoc for viewing go language documents (these programs are 5g.exe, 6g.exe, and so on on the Windows platform). These strange names follow the name of the Plan 9 operating system compiler, which means that the processor system is represented numerically ("5" for Arm, "6" for amd64-including Intel 64-bit processors-"8" for Intel 386). Fortunately, we don't have to worry about this, the go language provides a higher-level go language building tool that can handle compiling and linking tasks for us.

All the code in this article uses the Go 1 version syntax and has passed the GC test on Linux, Mac OS x, and Windows. The Go Language developer program allows all subsequent go 1.x versions to support go 1 backwards compatibility, so the code and examples here will apply to all 1.x series versions.

To download and install go, visit golang.org/doc/install.html, where download links and installation instructions are available. Go 1 provides source packages and binary form installation packages for FreeBSD 7+, Linux 2.6+, Mac OS X (Snow Leopard and Lion) and Windows 2000+, and can support all Intel 32-bit and AMD 64-bit processor architectures. Go also supports the ARM processor version of Linux, which provides pre-built go packages for the Ubuntu Linux release. When you read this, you may already have a go installer for other Linux distributions.

A program that uses the GC compiler uses a specific invocation convention (call Convention). This means that a program compiled with GC can only be linked to an external library compiled with the same calling convention-unless the differences are eliminated with a suitable tool. Use the CGO tool go to support the use of external C code in the Go program, and at least on the Linux and BSD systems, through the Swig tool we can use C and C + + code in the Go program.

In addition to GC, there is also a compiler called GCCGO. It is a go-specific front end for GCC, GCC 4.6 and later versions are supported. Like a GC, GCCGO may be built into some Linux distributions. The instructions for building and installing GCCGO can be found on the go main site.

Go documentation

An up-to-date go document is maintained on the go official site. The "Packages" link provides access to all the Go standard library packages-and their source code, which is useful when the documentation is scarce. Through the "Commands" link you can find documentation of the related programs that were published with Go (such as compilers, build tools, etc.). With the "specification" link, you can find an informal but comprehensive go language specification. With the "Effective Go" link, you can find a document that describes go best practices.

The site also provides a sandbox feature for writing online, compiling, and running Go applet (with a slight limit). This feature is useful for beginners to experiment with some wacky grammar. The search box on the go site can only be used to search the go document, and if you want to complete a full search of the Go resources, please visit http://go-lang.cat-v.org/go-search.

Go documents can also be browsed locally, for example in a Web browser. To do this, run the Go Godoc tool and tell it to run as a Web server by passing in command-line arguments. Here's how to do this in a UNIX or Windows console, assuming that Godoc is already set in the PATH environment variable:

$ godoc-http=:8000

The port number in this example can be arbitrary-if it conflicts with an existing server port, you can use any other port number.

To view the document, open a browser and enter the address http://localhost:8000. A page similar to the golang.org homepage will appear in front of you. The "package" link will point to the Go standard library and the documentation for the third-party packages installed under the GOROOT environment variable. If you define GOPATH environment variables (for example, local programs and packages), a link will appear next to the "Packages" link, where you can access other related documents. (Goroot and Gopath environment variables are discussed later in this article)

Edit, compile, and run

The Go program is written in normal Unicode text encoded with UTF-8. Most modern text editors can automatically process this code, and some of the most popular editors can support the syntax color highlighting of Go source and auto indent. If your editor does not support go, try typing your editor's name into the go search engine to see if there is a suitable plugin available. As an editorial practice, all go keywords and operators use ASCII letters, however, the go identifier can start with any Unicode letter, followed by any Unicode letters or numbers, so go developers are free to use their native language.

In order to master how to edit, compile, and run a go program, I began to use the classic "Hello World" program as an example-but I wrote this program slightly more complicated than usual.

If you have already installed go with a binary package or through the source, and are installed with root or administrator privileges, you should set at least one environment variable: goroot, which indicates the installation path information for go, your PATH variable should now contain $goroot/bin or%goroot%\ Bin To check that the go is installed correctly, enter the following command under the console:

$ go version

If you get the error message "Command not found" or "' go ' is not recognized ...", it means that there is no go at the path configured by the PATH variable.

Compiling and linking

Building a Go program takes two steps: compiling and linking. (since we assume that the GC compiler is used, readers who use the GCCGO compiler need to follow the compilation and linking process described in golang.org/doc/gccgo_install.html, as well, readers using other compilers need to compile and link according to their compiler's instructions). The compile and link process is handled by the tool go, which not only builds local programs and packages, but also gets, builds, and installs third-party programs and packages.

There are three requirements for go to compile local programs and packages. First, the bin directory of Go ($GOROOT/bin or%goroot%\bin) must be under the PATH environment variable. Second, there must be a directory, which contains a src directory, local programs and packages of source code resides in the SRC directory. For example, the example code will be unpacked to Goeg/src/hello, Goeg/src/bigdigits, and so on. Finally, the directory containing SRC must be set in the GOPATH environment variable. For example, to use the Go tool to build the example of hello, we have to do this:

$ export gopath= $HOME/goeg
$ cd $GOPATH/src/hello
$ go Build

Two examples, we all assume that the PATH environment variable contains $goroot/bin or%goroot%\bin. Once the go compiler is finished, we can run the program. By default, go uses the name of the directory in which the executable file is located (for example, Hello on Unix-like systems and hello.exe on Windows). Once the build is complete, we can run it as usual.

$./hello
Hello world!

Note that we do not need to compile or explicitly link other packages (even though we will see later, Hello.go uses three standard library packages). This is one reason why the GO program compiles so fast.

If we have multiple go programs, it would be very handy to have their executables in the same directory, and then simply add the directory to the PATH environment variable. Fortunately, go supports such situations:

$ export gopath= $HOME/goeg
$ cd $GOPATH/src/hello
$ go Install

The Go Install command also places executables in a standard location ($GOPATH/bin or%gopath%\bin), in addition to what go build does. This means that a single path ($GOPATH/bin or%gopath>%\bin) is added to the PATH environment variable, and all the go programs we install can be easily added to the path.

In addition to the examples given here, we are likely to want to develop our own go programs and packages in our own directory. By setting two (or more) colon-delimited paths for the Gopath environment variable (separated by semicolons on Windows), we can easily solve this problem.

While go uses the Go tool as a standard build tool, you can still use make or other modern build tools, or use other go-specific build tools, or plug-ins for some popular Ides.

Who Are you greeting (hello)?

Now that we've seen how to build a Hello program, let's look at its source code. The following is the full source of the Hello program (in file hello/hello.go):

Hello.go
Package Main
Import (
"FMT"
"OS"
"Strings"
)
Func Main () {
Who: = "world!"
If Len (OS. Args) > 1 {/* OS. Args[0] is "hello" or "hello.exe" */
who = strings. Join (OS. Args[1:], "")
}
Fmt. Println ("Hello", WHO)
}

Go uses the C + + style annotation symbol//As a single line comment, with/* ... */as a multiline comment symbol. As a rule, go uses a single-line comment, and multiline annotations are often used to comment out blocks of code in development.

Each go code is present in a package, and each go program must have a main package containing the main () function, where the main function acts as the entry point for the program execution, that is, the function executes first. In fact, the go package can also define the INIT function that executes before the main function. It is worth noting that there is no conflict between the package name and the name of the function.

The go operation is in the package, not the file. This means that we can arbitrarily split a package into multiple files, as needed. If more than one file has the same package declaration, the go language considers these files to be part of the same package, which is the same as all content in a single file. Of course, we can also break down the functionality of the app into many local packages, which keeps the code neat and modular.

Import statement imports three packages from a standard library. The FMT package provides functions for formatting text and for reading formatted text, OS packages provide platform-independent operating system variables and functions, and strings packages provide functions for manipulating strings.

The basic type of GO supports common operators (for example, + can be used for numeric addition and string connections), and the standard library of Go provides function package additions that operate on basic types, such as the strings package that is imported here. We can create our custom types based on basic types and define related methods for them-functions that customize the type of action attribute.

The reader may have noticed that there is no semicolon in the go source, and that the import package does not need a comma separated and that the IF condition statement does not require parentheses. In go, blocks, including function bodies and control structures such as for, if statements, and for loops, are defined using parentheses. Indentation is simply used to improve the readability of your code. Technically, go statements are separated by semicolons, but these semicolons are inserted by the compiler, and we don't have to care about them unless we want to put multiple statements in the same row. No semicolons, few commas, and parentheses make the Go program look more concise and require less input.

Go uses the Func keyword to define functions and methods. The main () function of the main package always has the same function signature – no arguments, no return values. When Main.main () ends, the program terminates and returns 0 to the operating system. Of course, we can return at any time and choose our own return value.

The first statement in the main () function (using the: = operator) is referred to as a short variable declaration in Go terminology. This statement declares and initializes a variable at the same time. In addition, we do not need to specify the type of the variable, because go can deduce the type of the variable based on the initial value. So in this example, we declare a variable of type string who, thanks to the strong typing mechanism of go, we simply assign the string to the WHO.

Os. The args variable is a slice (fragment) of a string. Go uses array (array), slice, and other collection data types, but in these examples, you know the following: Use the built-in Len () function to get the length of a slice and the elements that are accessed through the [] subscript operator. In particular, Slice[n] returns the nth element of slice (starting at 0), Slice[:n] returns another slice, the new slice consists of elements from the nth to the last of the original slice. In the collection chapter, we will see a general go syntax for this. Here's the OS. In the case of args, this slice should always have a string at least at position 0 (the name of the program). (All go subscript index is starting from 0)

If you enter one or more command-line arguments, the IF condition will be met, and we will stitch all the parameters into a single string and assign the value to WHO. In this example, we use the assignment operator (=), and if we use: =, we will declare and initialize a new who variable whose scope of influence will be confined to the IF statement block. Strings. The Join function takes a string slice and a delimiter (which can be empty, or "") as an argument, and returns a single string of characters separated by all slice string elements. Here we separate the strings with a space.

Finally, in the last statement, we output a hello, a space, a string in the WHO variable, and a new line (newline). The FMT package has many different print output variants, some like FMT. Println () will neatly output any incoming value, other such as FMT. printf will use placeholders to provide better formatting control.

Another example – two-dimensional slices

In the next example, the Bigdigits program reads a number from the command line (in a string form) and outputs this number using a "large font" on the console. As early as 20th century, when many users shared a high-speed line printer, it was customary to use this technique to place a cover page before each user's printing work, which could show details such as the user name and the name of the file to be printed.

I'll review the code for this program in three paragraphs: first, the import section, then the static data, and finally the process. But now let's take a look at a sample to see how this program works:

$./bigdigits 290175493

Each digit is represented by a string slice, and all the numbers are represented by an element that is the slice of the string slice. Before looking at the data, here we show how to declare and initialize a one-dimensional string and number slice:

Longweekend: = []string{"Friday", "Saturday", "Sunday", "Monday"}
var lowprimes = []int{2, 3, 5, 7, 11, 13, 17, 19}

Slice with []type, if we want to initialize them, we can immediately follow a list of elements of the corresponding type with curly braces wrapped, comma delimited. We could have declared these two variables with the same variable declaration syntax, but here we're going to show the difference between the two syntaxes and a reason to explain later, Lowprimes Slice uses a longer form of declaration. Because the slice type can be an element type of the slice type, we can easily create multidimensional collections (slice slice, etc.).

The Bigdigits program only needs to import four packages.

Import (
"FMT"
"Log"
"OS"
"Path/filepath"
)

The FMT package provides functions for text formatting and reading formatted text. The log package provides logging functions. The OS package provides platform-independent operating system variables and functions, including the []string type OS] that holds command-line parameter values. The args variable. The filepath package below the path package provides a correlation function for cross-platform operation file names and paths. Note For packages that logically contain relationships (such as Path/filepath), we use the code only to indicate the last part of its name (this is filepath).

For Bigdigits This program, we need a two-dimensional data (a string slice the slice). Here's how to create it, by representing the string layout of the number 0, we can see that the corresponding string of this number is the corresponding line at the output. The numbers corresponding to 3 to 8 are omitted here.

var bigdigits = [][]string{
{"000",
"0 0",
"0 0",
"0 0",
"0 0",
"0 0",
"000"},
{"1", "11", "1", "1", "1", "1", "111"},
{"222", "2 2", "2", "2", "2", "2", "22222"},
... 3 to 8 ...
{"9999", "9 9", "9 9", "9999", "9", "9", "9"},

Variables declared outside of a function or method can not be used: = operator, but we can use the Long declaration form (using the keyword VAR) and the assignment operator (=) to achieve the same effect, as we have here for the variables in the Bigdigits program (before facing the declaration of the Lowprime variable). We still don't need to specify the type of the bigdigits variable, and Go can infer its type from the assignment.

We left the computational work to the go compiler, so it is not necessary to point out the dimensions of the slice. One of the handy things about go is its good support for using parentheses to match the literal value so that we don't have to declare a data variable in one place and then assign it to it in another place.

The main () function reads the command line and uses the data to produce the output, which has only 20 rows.

Func Main () {
If Len (OS. Args) = = 1 {
Fmt. Printf ("Usage:%s \ n ", filepath. Base (OS. Args[0]))
Os. Exit (1)
}

Stringofdigits: = os. ARGS[1]
For row: = Range Bigdigits[0] {
Line: = ""
For column: = Range stringofdigits {
Digit: = stringofdigits[column]– ' 0 '
If 0 <= digit && digit <= 9 {
Line + = Bigdigits[digit][row] + ""
} else {
Log. Fatal ("Invalid whole number")
}
}
Fmt. Println (line)
}
}

The program starts by checking for any command-line arguments. If not, Len (OS. Args) will have a value of 1 (Recall, OS. Args[0] is the name of the program, so the length of the slice is at least 1). If the condition of this if statement is true, we will use FMT. printf outputs an appropriate program usage information that uses a% placeholder that is similar to the% operator in C + + in printf () or Python.

The Path/filepath package provides path manipulation functions-for example, filepath. The base () function returns the base name of the given path (basename, the file name). After this message is output, the program uses the OS. The Exit () function ends the program and returns 1 to the operating system. In a Unix-like system, a return value of 0 is used to indicate success, and a value other than 0 identifies a usage error or failure.

FilePath. The use of the Base () function shows us a wonderful feature of Go: When a package is imported, whether it is a top-level package or a package that is logically built into another package (for example: Path/filepath), we can always refer to it only by the last part of its name (that is, filepath). We can also give the package local names to avoid name collisions.

If at least one command-line argument is passed, the first parameter is copied to the Stringofdigits variable (string type). To convert a user-entered number into a large number, we have to iterate over each line of the bigdigits slice, that is, the first line of each number (the top row), the second line, and so on. We assume that all bigdigits slice have the same number of rows, so that we can get the number of rows from the first slice. The For loop of Go has different coping syntax for different scenarios, in this case, the For...range Loop returns the index position information for each element in the slice.

The code for the loop portion of the rows and columns can be written like this:

For row: = 0; Row < Len (bigdigits[0]); row++ {
Line: = ""
For column: = 0; Column < Len (stringofdigits); column++ {
...

This is a syntax form that C, C + + and Java programmers are familiar with, and it works in go. (unlike C, C + + and Java, in go, the + + and – operators can only be used as statements, not as expressions.) In addition, they can only be used as postfix operators, not as prefix operators. This means that problems related to the order of evaluation will not occur in go-thank goodness, expressions such as f (i++) and a[i] = b[++i) are illegal in go. However, the for...range syntax is much shorter and more convenient.

At each iteration of the line, the code assigns line lines to an empty string. Next, we do iterative processing of the columns (that is, characters) in the Stringofdigits obtained from the user. The go string uses UTF-8 characters, so essentially one character is likely to be represented in two or more bytes. But this is not the topic to be discussed here, because we only care about the values 0, 1 、...、 9, these values are represented by UTF-8 characters with only one byte, which is the same as the byte values used in 7-bit ASCII characters.

When we index a particular position in a string, we get the byte value of that location. (In Go, the byte type is a synonym for the uint8 type.) So we get the byte value on a particular column of the command line string, minus the byte value of the number 0, and get the number it represents. In UTF-8 (and 7-bit ASCII), the character ' 0 ' is the code point (character) decimal value 48, the character ' 1 ' is the code point decimal Value 49, and so on. So for example, if we have the character ' 3 ' (Code point 1), we can get its integer value 51-48 by doing subtraction ' 3 ' – ' 0 ' (or 3) result.

Go uses single quotes to denote character literals, and a character literal is an integer that is compatible with any integral type of go. The strong type of go means that we cannot add the number of a int32 type to the number of a int16 type without an explicit transformation, but the numeric constants and literals in Go are adapted to their context, so that ' 0 ' is considered to be a byte.

If this number (byte type) is in range, we will add the corresponding string to the line variable. (in the If statement, constants 0 and 9 are considered byte types because they are numeric types, but if the values are a different type, for example, int, they will be treated as a new type.) Although the string in go is immutable, go still supports the + = add-on operator to provide an easy-to-use syntax. (It replaces the original string by replacing it in the background.) Go also supports the + string join operator, which returns a new string that is connected by the left and right string operands.

In order to get the corresponding string, we access bigdigits slice based on this value, and then access the row (string) where we need it.

If the value is out of range (for example, because Stringofdigits contains a non-numeric value), we call log. The Fatal () function logs an error message. If no other log output target is explicitly specified, this function will be on the OS. The date, time, and error messages are recorded in the stderr. The function then calls the OS. Exit (1) closes the program. There is also a name log. The Fatalf () function can do the same thing, but it accepts the% placeholder. We did not use log in the first if statement. Fatal () function, because we want to output the program's usage information, but do not log. Fatal () The default output date and time information.

Once the string of all the numbers for a given line is accumulated, the complete line is output. Here, we output 7 rows, because the number in each bigdigits slice is represented by seven strings.

The last point is that the order of declarations and definitions does not matter. So in the Bigdigits/bigdigits.go file, we can declare the BIGDIGITS variable before the main () function, or we can declare it later. In this example, we put the main () function in front, and for the example in this article, we tend to prefer the top-down sort.

The two examples here already cover a number of features, but the information they show is similar to other mainstream languages, even though the syntax is slightly different. Next week's article will look at the rest of the go language features, including some advanced aspects.

, Bigwhite. All rights reserved.

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.