This is a creation in Article, where the information may have evolved or changed.
This article is from Google's official translation: How to Write Go Code?
Http://godoc.golangtc.com/doc/code.html
Introduced
This document illustrates an example of a simple go package and introduces a go tool
standard way to fetch, Build,and install go package and commands.
If you want to use the Go tool, you must organize your code into a special form. Please read this document carefully and it will teach you the simplest way to install and run your go program.
Code Organization
Workspace Working space
The Go tool is designed to be used for code in an open source public repository, although you may not need to publish your code, but the environment is set up the same way.
The source code of go must be stored in the workspace. Workspace is a directory (directory hierachy) with three subdirectories in this directory
src
Includes Go source code file, source code file organized into packages (one package per directory)
pkg
Contains Package objects (binary packages)
bin
Contains executable command commands (executable binaries)
The Go tool compiles (build) source code files (sources packages) and installs the resulting binaries under the pkg
and bin
directory.
The SRC directory contains multiple versioning repositories, such as Git or Mercurial, to track the development progress of one or more source package.
Here's what it looks like in a real-world workspace:
Bin/hello# commands that can be executedOutyet# commands that can be executedPkg/linux_amd64/github/golang/example/stringutil. A # Pakcage ObjectsSrc/github. com/golang/example/. Git/# git repository metadataHello/hello. Go # command SourceOutyet/main. Go # command SourceMain_test. Go # test SourceStringuitl/reverse. Go # package SourceReverse_test. Go # test Source
This workspace contains a code warehouse repository (example warehouse), example warehouse consists of two command commands (hello, outyet) and one library (stringutil)
A typical workspace will contain multiple source repositories, including many pakcages and commands.
Most go programmers will keep all their go source code and dependencies in a single workspace. (Save all Go source code and dependencies in one workspace).
Also from the above example can be seen, the name of the command in bin/, pkg/the name of the library is the text of the folder. The name of the package in src/is not necessarily the same as the name of your import, which is different.
Gopath Environment variables
GOPATH
Environment variables indicate the location of your workspace. It is probably the environment variable that you need to set only when you write the go code.
Start Programming:
1. Create a workspace directory.
2. Set the GOPATH environment variable.
The Gopath directory can be arbitrary, and the only requirement is that it cannot be the directory where you install Go (/usr/local/go).
$ $HOME/go$ GOPATH=$HOME/go
For convenience, add the bin subdirectory of the workspace to your PATH
environment variables.
export PATH=$PATH:$GOPATH/bin
Package Pathes Packet Path
Packages path is not the library path, although they are linked.
Packages in the standard library are determined by short path, such as "FMT" and "net/http". For your own package, you must select a base path, which cannot conflict with other packet paths.
If you save your code in a source repository, then you should use the root of that source repository as your base path.
For example, you have a GitHub account: github.com/usr
This should be your base path.
Note: You may not need to post your code to the remote repository before you can build it. But it's a good habit to make code repository.
Example: We use github.com/usr
as your base path. Create a directory in your workspace to save your code.
$ $GOPATH/src/github.com/usr
First Program
To compile and run a simple program, first select a package path (use GITHUB.COM/USR here) to create a packages directory
$ mkdir $GOPATH/src/github.com/usr/hello
Second: Create a file in the package directory named hello.go
, containing the following code
package mainimport"fmt"func main() { fmt.Println("Hello, World.\n")}
Third: Use the Go tool to build and install the program
$ go install github.com/user/hello
Note: You can run this command under any folder on your computer. The package is searched under the go tool
$GOPATH
specified workspace github.com/usr/hello
, and the package is compiled and installed.
Of course, you can ignore package path if you run it under package directory go install
.
$ $GOPATH/github.com/usr/hello$ go install
This command hello
generates an executable binary file. The executable binary is then installed under the directory of the working directory, and the bin
file name hello
is called (under Windows hello.ext
, you can see that the executable binary file name and the directory name remain the same). In our case, it is: $GOPATH/bin/hello
$HOME/go/bin/hello
When an error occurs, go tool
only print output is generated, not the binary file. If these commands do not produce output, it means they are running successfully.
Now you can hello
run this command by entering the full name of the command.
$ $GOPATH/bin/hellohello, world
Or if you are already $GOPATH/bin
added to the PATH
medium:
$ hellohello, world
If you use source code version control system, now this is a good time to initialize a repository, add the Files,and commit you first Chagne. Again, this step is optional:you does not need to the use of source control to write Go code.
$ cd $GOPATH/src/github.comin /home/user/go/src/github.com/user/hello/.gitadd hello.go"initial commit"0b4507d] initial commit 11 insertion(+) 100644 hello.go
Push the code to the remote repository and leave it as a contact for the reader.
First Library
Now let's write a library and use it in the Hello program.
- First, select a package path (which we use
github.com/user/stringutil
) to create this package directory
$ $GOPATH/src/github.com/usr/stringutil
- Create a file
reverse.go
in this directory
//package Stringutil Contains utility functions for working with strings. //reverse returns its argument string reversed run-wise left to right. func Reverse (S string ) string {r: = []rune (s) for i, J: = 0 , Span class= "hljs-built_in" >len (R)-1 ; I < len (R) /2 ; I,j = I+1 , J-1 {r[i], r[j] = R[j], R[i]} return string (r)}
- Test This pckage compiles with command
go build
:
$ go build github.com/user/stringutil
Or if you're under this directory, you just need to
$ go build
Can.
go build
No files are generated. We need to use the go install
pkg directory where the package object can be placed under workspace.
$ go install
- In order to confirm
stringutil
that we have established (build), we need to modify the hello.go
file.
package mainimport ( "fmt" "github.com/usr/stringutil")func main() { fmt.Printf(stirngutil.Reverse("!oG, olleH"))}
- When the Go tool installs a package or a binary (executable binary), it also installs whatever dependencies it has (installs the files it depends on). So when you intall
hello
the program,
go install github.com/user/hell
stringutil
will also be installed automatically.
Running the new version of the program, you will see the following results:
$ helloHelloGo!
After the above steps, your workspace should now be the following:
bin/hello # Comman d executalbe executable command pkg/linux_amd64/# this would reflect you OS and arch Itecture github.com /usre/stringutil.a # package object Src/github.com /user/hello/hello.go # command source stringutil/reverse.go< /span> # package source
As you can see, go install
stringutil.a
This directory will be placed in pkg/linux_amd64
the directory mirrors its source directory. This is because the Go tool will find the package object in the future and will avoid recompiling. linux_amd64
is for platform cross-compilation, which will reflect the architecture of your operating system and your computer.
Go command Exectualbes is statically linked. (Go command execution is statically linked) the package objects need is present to run Go program. (Pakcage object is not required when the Go application executes).
Package names
In the go source file, the first line of the statement must be
package name
Where is the package's name
default name for imports. (All files in a package must use the same name
)
The Convention of Go is that the package name is the last element of the import path: for example, the imported packages are "crypto/rot13"
then, and it should be rot13
. (In fact, the imported package name does not have to be consistent with the actual packages name.) Because the package being imported is the directory in which it resides, the directory in which it resides is not necessarily consistent with package name. But the formula is the same. )
The executable command must use thepackage main
The package name is not necessary in all packages (linked to a single binary) is the only, Yo Ah import path (their full file name) is unique.
Testing
Go has a lightweight test framework: tesing. Testing consists go test
of commands and testing
packages.
The testing can be used as a unit test or as a stress test.
How to write unit tests using testing:
1. Create a file that ends with this file _test.go
, for example: reverse_test.go
2. This file contains the test function: Testxxx, where the starting character of XXX must not be a lowercase letter [a-z], the test function signature is: Func (t *testing. T).
The testing test framework runs each test function, and once the test function calls the failure function, such as: t.Error
or t.Fail
, the test indicates a failure.
Example:
1. Add a test file to the Stringutil
package. That is, create the file $GOPATH/src/github.com/user/stringutil/reverse_test.go
, which contains the following code
package stringutil Import "testing" func testreverse (t * Testing. T) {cases: = []struct {in, want string } {{ "Hello, World" , "Dlrow, Olleh" } { "Hello, Go" , "OG, Olleh" } { "" , }} for _, c: = range case {got: = Reverse (c, in) if got! = c.want {T.errorf (" Reverse (%q) = =%q, want%q ", c.in, got, c.want)}}}
- Run test Cases
$ go test github.com/user/stringutilok github.com/user/stringutil 0.165s
As always, if you are running under Package directory go tool
, you can ignore the package path.
$ go testok github.com/user/stringutil 0.165s
If you have questions, run go help test and look at the testing package documentation for more information.
Remote Packages (remotely package installation)
go tool
Can be used to automatically fetch packages from remote repositories. (such as Git or Mercurial).
For example, github.com/golang/example
there is the code we wrote above on Github. If you include this repository URL in the package's import path, the go get
command will automatically be the fetch build and install
packet. (Auto get, build, install this package)
$ go get github.com/golang/example/hello$ $GOPATH/bin/helloHelloGo examples!
If the specified package is not in workspace, then the go get
command will place it in the $GOPATH
first workspace specified. (If the package already exists, the go get
remote fetch will be ignored, and go install
the same action is performed)
After the issuing go get
command, the current workspace should look like this:
Bin/hello# commands that can be executedPkg/linux_amd64/github/golang/example/stringutil. A # Pakcage ObjectsGithub/user/stringutil. A # Package ObjectsSrc/github. com/golang/example/. Git/# git repository metadataHello/hello. Go # command SourceOutyet/main. Go # command SourceMain_test. Go # test SourceStringuitl/reverse. Go # package SourceReverse_test. Go # test SourceGitHub. com/user/hello/hello. Go # command SourceStringutil/reverse. Go # package SourceReverse_test. Go # test Source
The hello command in GitHub relies on stringutil in the same code repository. Imports in the Hello.go file need to use the same Import Path Convention (Convention) so that the go get
command can locate and install the dependent package.
import "github.com/golang/example/stringutil"
This practice is very important, we must abide by it. And this routine can make your package easy for others to use.
The Go wiki and godoc.org provide some of the columns of the external go progects.
What ' s next? (What to do next)
Subscribe to the golang-announce mailing list So you'll be notified when a new go version comes out.
Read effective go to write a clean and beautiful go code.
Read A Tour of Go to learn the grammar of Go
Visit the documentation Page with some articles to get a deep understanding of the Go language and its tools, as well as its libraries.
Take a look at Go documentation There are a lot of good resources too.
Take a look at the Go command to learn more about the use of the Go command.
Go Nuts Official discussion list of Go language.