How to write Go code

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

1: Code Organization

Go developers usually put all the go code in a separate workspace. A workspace can contain multiple version control libraries (such as Git), each containing several package, each of which contains one or more go source files, and the directory path determines his reference path;

There are usually 3 subdirectories under workspace: src contains the go source file, the pkg contains the package object, and the bin contains the executable program. Go compile, build src in the Go source code, and the compiled binary files installed in the Pkg and bin;

Here is an example of a workspace:

bin/hello # command executable Outyet # Command EXECUTABLEPKG/LINUX_AMD64/GITHUB.COM/GOLANG/EXAMPLE/STRINGUTIL.A # PAC            Kage objectsrc/github.com/golang/example/. git/# git repository metadata hello/            Hello.go # command Source outyet/main.go # command source            Main_test.go # Test Source Stringutil/reverse.go # package source        Reverse_test.go # Test Source golang.org/x/image/. git/# git repository metadata Bmp/reader.go # package Source Writer.go # package Source ... (many more repositories and packages omitted) ... 

The workspace above contains two repositories: example and image. The example library contains 2 executables: Hello and Outyet, a library file stringutil. The image Library contains BMP and other package.

2:gopath Environment variables

The environment variable Gopath indicates the location of the workspace. By default, the value of this environment variable is a subdirectory named go in the HOME directory, such as C:\Users\YourName\go under $home/go,windows under UNIX.

Specify the exact location of the workspace by setting the Gopath. Note that Gopath cannot be set to the same as the Go installation directory.

The Go env gopath command can print out the current value of Gopath.

3: Reference Path (import path)

The reference path is used to uniquely identify a package. The reference path pair of the package should be packge relative to the location in workspace, or the address of a remote library.

The package reference paths in the standard library are short paths such as "FMT" and "net/http". For the package you define, you must select a base path that does not conflict with the standard library.

For example, with Github.com/user as the base path, you need to create the corresponding directory in workspace:

Mkdir-p $GOPATH/src/github.com/user

4: The first program

The first is to determine the package path, the path used here is Github.com/user/hello, and the corresponding directory is created in workspace:

mkdir $GOPATH/src/github.com/user/hello

Then in the above directory to create a new source file Hello.go, the content is as follows:

Package Mainimport "FMT" Func Main () {    fmt. Printf ("Hello, world.\n")}

You can then compile, build, and install the package:

Go Install Github.com/user/hello

The above commands can be executed anywhere within the system. Go compiler can get workspace path through Gopath environment variable, and then find the source code in Github.com/user/hello this package.

The Go Install command builds Hello, generates an executable file, and installs the file into the bin directory in workspace. Run the program as follows:

$GOPATH/bin/hellohello, World.

5: First Library

The first is to identify the package path and create the corresponding directory in workspace:

mkdir $GOPATH/src/github.com/user/stringutil

Next, create the Reverse.go source file in this directory, with the following content:

Package Stringutil contains utility functions for working with Strings.package stringutil//Reverse returns its argumen T string reversed Rune-wise Right.func Reverse (s string) string {    r: = []rune (s) for    I, J: = 0, Len (r)-1; I < Len (r)/2; I, j = i+1, j-1 {        r[i], r[j] = R[j], r[i]    }    return string (r)}

Then, use the Go Build command to verify that the compilation succeeds:

Go Build Github.com/user/stringutil

The above command does not produce an output file. You must use the Go Install command to generate a package object under the PKG directory.

Next, modify the Hello.go file as follows:

Package Mainimport (    "FMT"    "Github.com/user/stringutil") func main () {    fmt. Printf (Stringutil. Reverse ("!og, Olleh"))}

When go compiles a package or binary, it also installs its dependencies. Therefore, when you install Hello, the stringutil it relies on is also automatically installed:

Go Install Github.com/user/hello

  

Run the new program with the following results:

Hellohello, go!

Now, the contents of workspace are as follows:

bin/    Hello                 # command executablepkg/    linux_amd64/          # This would reflect your OS and architecture        github.com/user/            STRINGUTIL.A  # package objectsrc/    github.com/user/        hello/            hello.go      # Command source        stringutil/            reverse.go    # package source

The Go Install command installs the Stringutil.a file in the Pkg/linux_amd64 directory, which corresponds to the subdirectory of the source code. As a result, the compiler can find the package file at subsequent compile time to avoid unnecessary recompilation. "Linux_amd64" is primarily used for cross-platform compilation, to identify the operating system and CPU architecture.

The go executable is statically linked, and the package object file does not have to exist when you run the Go program.

6:package Name

The first declaration statement in the go source file must be: Package name

The name is the reference name of the package, and the source code file in the same document must use the same name.

The Convention of Go is that the package name is the last element of the reference path, such as the package with the reference path "crypto/rot13", which is named ROT13.

The executable must use main as the package name.

When multiple package links are linked into a binary file, the names of these are not necessarily unique, as long as they have different reference paths.

7: Test

Go has a lightweight test framework that includes the Go Test command, as well as the testing package.

When writing the test code, the source file name needs to end with "_test.go", and the function is in the form of Func testxxx (T *testing. T).

The test framework runs each of the test functions, if the function calls to T. Error or T.fail, indicating that the test failed.

For example, if you need to test Stringutil This package, you can create a file $gopath/src/github.com/user/stringutil/reverse_test.go, which reads as follows:

Package Stringutilimport "Testing" func testreverse (t *testing. T) {    cases: = []struct {in]        , want string    } {        {"Hello, World", "Dlrow, Olleh"},        {"Hello, Worlds", "Realms, Olleh "},        {" "," "},    } for    _, c: = Range Cases {        got: = Reverse (c.in)        if got! = c.want {            T.errorf (" Rev Erse (%q) = =%q, want%q ", c.in, Got, C.want)}}}    

To run the test code:

Go Test Github.com/user/stringutilok      github.com/user/stringutil 0.165s

Alternatively, if you are currently in the package directory, you can run the Go Test command directly:

Go testok      github.com/user/stringutil 0.165s

8: Remote Package

The package reference path can also be used to describe how to get the source code from a version control system such as Git or mercurial. The go compiler can use this feature to get the package from the remote repository.

For example, the code in the example above also exists in the GIT library: github.com/golang/example. If the reference path uses the URL address in the source code, you can use the go get command, which pulls the package from the remote and compiles the installation:

Go get Github.com/golang/example/hello$gopath/bin/hellohello, go examples!

If the package is not in the current workspace, go get will be placed under the workspace specified by Gopath, and if the package already exists, then go get will omit the remote pull process, the rest of the action is the same as go install.

After you finish running the go Get command, the workspace directory hierarchy is as follows:

bin/    Hello                           # command executablepkg/    linux_amd64/        github.com/golang/example/            STRINGUTIL.A            # Package Object        github.com/user/            stringutil.a            # package objectsrc/    github.com/golang/example /    . git/                       # git repository metadata        hello/            hello.go                # command source        stringutil/            Reverse.go              # package source            reverse_test.go         # test source    github.com/user/        hello/            Hello.go                # command source        stringutil/            reverse.go              # package source            reverse_test.go         # Test source

You can re-edit the Github.com/user/hello/hello.go file to

Import "Stringutil"

Switch

Import "Github.com/golang/example/stringutil"

This way, when you execute go get Github.com/user/hello, you will first download the package from the remote Stringutil and then compile and install hello.

Https://golang.org/doc/code.html

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.