How to write Go code

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

Catalogue [−]

    1. code organization
      1. Workspace workspace
      2. < Span class= "Toc-text" >gopath environment variable
      3. package Path
      4. first Go program
      5. first go library
      6. Package name
    2. test
    3. remote package
    4. next
    5. ask for help

Official text: How to Write Go Code,
According to the latest official document translation. Translation reference Wang_yb How to write the Go code.
Since the official documentation has been updated, I have re-translated it according to the new version of the document.

This article demonstrates how to develop a simple go package and how to use the Go tool,
The standard methods and commands for getting (fetch), compiling (build), and installing the Go package.

The Go tool requires you to organize your code according to certain criteria. Please read this article carefully.
It describes the simplest way to build and run a Go program.

This article describes the video reference: Https://www.youtube.com/watch?v=XCsL89YtqCs.

Code Organization

Work Area Workspace

The Go tool is designed to work with open source code in public repositories.
Even if you don't need to publish your code, the Go tool's working model also works for you.

The Go code must be saved in the workspace, and the workspace is a specific directory structure with the following 3 directories in the root directory:

    • src directory: Store go source files, organized by package (one package folder)
    • pkg Catalog: Store Package objects
    • bin directory: Store executable command commands

The Go tool compiles the files under src and puts the compiled binaries into the pkg or bin folder respectively.
The src directory can contain multiple versioning repositories (such as Git or Mercurial) to manage code development.

The directory structure of an actual workspace is as follows:

123456789101112131415161718
Bin/hello #Command executableOutyet #Command executablePkg/linux_amd64/github.com/golang/example/stringutil.a# package Objectsrc/github.com/golang/example/. git/# git repository Metadatahello/hello.Go#Command SourceOutyet/main.Go#Command SourceMain_test.Go# testSourcestringutil/Reverse.Go# PackageSourceReverse_test.Go# testSource

This workspace contains a warehouse (example) consisting of two commands (Hello and Outyet), and a library (stringutil).

A typical workspace may contain many source repositories, which contain n-Multiple package and command. Most go programmers put their source code and dependencies in a single workspace.

command commands and library libraries are compiled by various source package. We'll introduce it later.

Gopath Environment variables

GOPATHThe environment variable points to the location of your workspace . This is the only environment variable you need to set when you develop the Go code.

When you start development, create a folder for the workspace and set the corresponding GOPATH environment variables.
Your workspace can be any folder, and the path used in this article is$HOME/work
Be careful not to GOPATH set the installation path to go. (Another common setting is set GOPATH=$HOME )

12
$HOME Export Gopath=$HOME/work

To facilitate the execution of the compiled command, add the above bin directory to PATH:

1
Export Path=$PATH:$GOPATH/bin

For more information on setting Gopath environment variables, you can view go help Gopath

Package path

The package in the standard library can only be used with short paths, such as "FMT", "net/http".
For your package, you must select a basic path to prevent future conflicts with the standard library, or other third-party libraries.
If your code is stored in a code warehouse, you can use the root directory of that code repository as the base path for your package.
For example, if you have a GitHub account github.com/user , you can use it github.com/user as your basic path.

Note that you do not need to publish your code to the remote code repository until you can compile the code correctly.
But if you release the Code one day, it's a good habit to organize your code.
In fact, you can use any path name, as long as it is unique in the Go standard library and the huge go ecosystem.
We use "Github.com/user" as the base path and then create a folder in the workspace to save the code:

1
$GOPATH/src/github.com/user

First Go Program

To compile and run a simple GO program, first determine the package path (using Github.com/user/hellohere),
and create the corresponding package folder in the workspace.

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

Next, create the Hello.go file in the folder above, with the following file contents:

1234567
 Package mainimport"FMT"func Main () {FMT. Printf ("Hello, world.\n")}

You can then use the Go tool to compile and install the Hello program above.

1
$ go Install Github.com/user/hello

Note that you can run the above command from any path, and the Go tool will look for Github.com/user/hello from the workspace based on the GOPATH environment variable.
If you run go install in the folder where the package is located, you can omit the package path.

12
CD $GOPATH/src/github.com/user/hello$ Go Install

The command above compiles the Hello command and produces the binary executable for this command.
The binary file Hello is then installed under the Bin folder of the workspace (Hello.exe under Windows)
In our case, it is $GOPATH/bin/hello, $HOME/work/bin/hello.

The Go tool only outputs information if there is an error, and if the go command above does not have an output, the execution succeeds.
You can then run the command on the command line.

12
$GOPATH/bin/hellohello, world.

Alternatively, if you add $GOPATH/bin to PATH, you can also execute the Hello command.

1
$ hello

If you use the Code versioning tool, you can initialize your repository, add files, and commit your first change.
Of course this step is optional, and writing the Go Code does not force the use of code versioning tools.

12345678
CD $GOPATH inch "Initial Commit" 0 1 1 insertion (+)  100644 hello.go

You can publish this warehouse as an exercise.

First Go Library

Let's write a library and use it in the Hello program above.
Again, first determine the package path (use Github.com/user/stringutil here) and create the corresponding folder.

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

Next, create the file reverse.go, which reads as follows:

 1234567891011 
 //package stringutil contains utility functions for working with strings.  package  stringutil//Reverse returns its argument string reversed Rune-wise left to 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)} 

Use go build to compile this package:

1
$ go Build github.com/user/stringutil

or in the package directory, run the go build directly

1
$ go Build

The above command does not produce an output file. In order to generate the output file, you must use the go install command, which generates the package object under the Pkg folder.
After the Stringutil package has been compiled successfully, modify the previous Hello.go file:

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

Whether you install the package object or the binary file with the Go tool, it installs all dependencies.
So when you install the Hello program,

1
$ go Install Github.com/user/hello

The Stringutil package will also be installed automatically.

To run the new Hello program, you can see the following output:

12
$ Hellohello, go!

After the above steps, your workspace should look like this:

 123456789101112 
 Bin/hello # command  executable  PKG/LINUX_AMD64/# This would reflect your OS and  architecture Github.
       
        com /user/stringutil. 
        a  # Package Objectsrc/github. 
        com /user/hello/hello. 
        go  # 
        command  
        source  str ingutil/
        reverse .

        go  # package 
        source  
       

Note that go install puts STRINGUTIL.A into the directory under the Pkg/linux_amd64 folder that corresponds to the source code.
Later, the Go tool can find the package to determine if it needs to be recompiled.
LINUX_AMD64 is the system that is currently in use, and it is designed to differentiate the package of other platforms that are cross-compiled.

The binaries compiled by Go are statically linked, so the above Bin/hello does not need to LINUX_AMD64/GO-FILES/STRINGUTIL.A files when it is executed.

Package Name

The first line of the go code file must be:

1
 Package Name

The name here is the default name for the package, which is used when the other package is import. (All files in the same package must use the same name).
Go Convention Package name is the last part of the import path.
In other words, if a package is quoted as "Crypto/rot13", then the package name is ROT13.

The package name that compiles the code for the executable must be main.

The package name that is connected to the same binary is not necessarily unique, as long as the import path of Pakage is unique.
That is, the above crypto/rot13 must be unique, but there can be another-crypto/rot13.

Go naming rules can refer to: [Effective go] (http://golang.org/doc/effective_go.html#names)

Test

Go contains a lightweight test framework, consisting of go test commands and testing package components.

The name of the test file ends with a _test.go function that contains func TestXXXX(t *testing.T) the format.
The test framework executes each of these functions, and if the function is called t.Error or t.Fail , the test is considered to be unsuccessful.

Add test files to the package stringutil above, path: $GOPATH/src/github.com/user/stringutil/reverse_test.go , the following:

12345678910111213141516171819
 Package stringutilImport"testing"func testreverse (t *testing. T) {cases: = []structstring}{{"Hello,World""Dlrow, Olleh"},{"Hello, Worlds"  "World, Olleh"},{"" "},} forrange Cases {got: = Reverse ( c.in)if got! = c.want {T.errorf ("Reverse (%q) = =%q, want%q", c.in, got, C.want)}}}

Here's how to run your tests:

12
$ go Test Github.com/user/stringutilok  0.165s

Or go to the package Stringutil directory and run it directly:

12
$ go testok  0.165s

Go to the Go test framework by going to help test or http://golang.org/pkg/testing/.

Remote Package

The Go's import path indicates how to get the package's source code from the version management system (Git or Mercurial). The Go tool can take advantage of this feature to automatically get the remote repository code.
For example, the code used in the following example is also stored on GitHub (http://github.com/golang/example).
If you import the above remote package in your code, then the go get command will automatically get, compile, and install it.

123
$GOPATH/bin/hellohello, Go examples!

If no package is specified in the workspace, the go get command will download the package to the first workspace defined in Gopath.
(If the package already exists, go get it will skip getting this step and perform go install the same behavior)

After the go get command above executes, the folder structure is roughly the following:

12345678910111213141516171819202122
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 Sourcestringutil/Reverse.Go# PackageSourceReverse_test.Go# testSourceGitHub.com/user/hello/hello.Go#Command Sourcestringutil/Reverse.Go# PackageSourceReverse_test.Go# testSource

The Hello program on github.com relies on the package stringutil in the same warehouse,
The hello.go on the github.com refers to the package stringutil on the github.com, so the go get command also downloads, compiles, and installs the Stringutil module.

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

This feature makes it easy for your go package to be used by others.
Many third-party go projects are listed on the Go Wiki and godoc.org.
For more information on using the Go tool to use a remote repository, please refer to: Go help Importpath

Next

    • Subscribe to the Golang-announce mailing list to learn about the latest Go release information
    • Use effective go as a reference to write neat, authentic go codes
    • Complete a go trip with A tour of Go
    • Visit Documentation page to learn a series of in-depth articles about the go language, as well as go libraries and tools.

Ask for help

    • For real-time help, you can use Freenode's IRC server #go-nuts
    • Go Language official mailing list go Nuts
    • To report a bug in the Go language, please use go issue tracker
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.