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.

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

Introduction (Introduction)

This article contains a simple go package and development process, as well as introduction to the use of go tool .

The Go tool requires a fixed organization of your code. Please be certified to read this article and it will take you how to start your Go programming tour in the simplest way.

Of course, we also prepared an intuitive video

Code Organization (Coding organization)

Workspaces

The Go tool is used primarily for open source code in a variety of public libraries. Although you may not be planning to publish your code, the environment configuration should be the same.
Go code needs to be organized in a workspace, and a workpace is worth a hierarchical directory structure with 3 Basic subdirectories in its root directory

    • src contains go source code files (organized in a code package, a subdirectory of a code package)
    • pkg contains the target file for the package, similar to the compilation target file in other languages
    • bin contains executable files

The Go tool will compile the source code package and install the binaries into the pkg directory and bin directory
src subdirectory contains and tracks source code from various version control repositories

Here is a practical example of a workspace:

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           # test SourceStringutil/reverse. Go             # package SourceReverse_test. Go        # test Source

The workspace contains a code base (example), two final command-line programs (Hello and Outyet), and a library file (Stringutil). You can see the relevant source code directly on GitHub.
A typical workspace will contain multiple code packages and multiple executable programs, and most of the Go program apes keep all their go codes and dependencies in a single workspace.

Executable programs and library files will be compiled from different source code packages, which we will discuss later.

The GOPATH environment variable

The gopath environment variable is used to indicate the location of the workspace, which is almost the only environment variable you need to set during the development of the GO program.

Next, we'll create a workspace directory and set the environment variable gopathfor it. Your workspace can be located anywhere, where we use $HOME/work . Note that the directory cannot be the Go installation directory (another common setting is GOPATH=$HOME )

$ $HOME/work$ GOPATH=$HOME/work

For convenience, you can add the workspace bin directory to your path directory

export PATH=$PATH:$GOPATH/bin

Learn more about the use of Gopath, see go Help Gopath

Package paths

Code packages from the standard library have short pathname names like "FMT" and "net/http". So in your own code package, you need to try to choose a base pathname that will not conflict with the standard library and some third-party library names.

If you keep your source code in a codebase, you should use the root of the codebase as your base pathname. For example, if you have such a path on GitHub github.com/user, you should use it as the base path for your code package.
Note that before your code can be compiled, you do not need to publish your code in the remote repository. If you want to publish it someday, organizing the code will be a good habit. Of course you can actually use any pathname, as long as you don't have a naming conflict with the standard library and some common third-party libraries.

Next we assume that we use Github.com/user as our base pathname to create its corresponding directory structure in the workspace:

$ $GOPATH/src/github.com/user

Your First Program

Next we will compile and run a simple program, first select a package path (here we use Github.com/user/hello) and create the corresponding directory in the previously set workspace

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

Next, create a hello.go file in this directory with the following content:

package mainimport"fmt"func main() {    fmt.Printf("Hello, world.\n")}

Below we can use go tool to compile and install the program

$ go install github.com/user/hello

Note that this command can be run anywhere on your file system, and thego tool will find the Github.com/user/hello directory under the corresponding workspace by Gopath .
If you are in the directory where the package is located, you can ignore the path name to run go install, as follows:

$ $GOPATH/src/github.com/user/hello$ go install

The go install command compiles the Hello code, generates an executable file, and installs the executable file in the bin directory under the workspace directory, named Hello (under Windows is Hello.exe). In our example, it will be $GOPATH/bin/hello , that is $HOME/work/bin/hello .

The go tool produces output only when an error occurs, so if there is no output during the execution of these commands, they are executed successfully.

Next you can run the code that you just compiled and installed:

$ $GOPATH/bin/helloHello, world.

If you have already $GOPATH/bin added the directory to your path directory, you can call it directly by program name:

$ helloHello, world.

If you use a git-like code control system, now is the time to commit it. Of course, these are only optional.

$ cd $GOPATH/src/github.comin /home/user/work/src/github.com/user/hello/.gitadd hello.go"initial commit"011 insertion(+)  100644 hello.go

Push the code to the far end of the warehouse as a reader's own contact, no longer repeat here.

Your First Library

Let's write a code base and use it in the Hello sample Program
Similarly, we will select a code package path (use Github.com/user/stringutil here) and create the appropriate directory

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

Next, create a file named Reverse.go in the directory

//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 , 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)}  

Now, we use go build to compile it

$ go build github.com/user/stringutil

If you are under the directory of the code package, you can also directly

$ go build

The command does not produce the corresponding executable file, only the go install command is available. In this case they will produce the corresponding target file in the PKG directory of workspace.

After confirming that the Stringutil package has been compiled correctly, modify the Hello.go (under the $gopath/src/github.com/user/hello directory) to use the method we just wrote.

$GOPATH/src/github.com/user/hello) to use it:package mainimport (    "fmt"    "github.com/user/stringutil")func main() {    fmt.Printf(stringutil.Reverse("!oG ,olleH"))}

Regardless of whether the go tool is used to compile and install an executable or a code package, he will compile and install its dependent content, so when you install the Hello program

$ go install github.com/user/hello

Stringutil package is automatically compiled and installed
Run this program:

$ helloHelloGo!

After all these steps, your workspace should have become

bin/hello # Comman D executable  pkg/linux_amd64/# this would reflect your OS and architect Ure  github.com /user/stringutil.a  # package object  src/github/user/hello/hello.go  # command source  stringutil/reverse.go  # package source   

Note that the go install command stringutil.a places the target file in the pkg/linux_amd64 directory so that future references can find the code package directly in the directory and prevent it from being recompiled. LINUX_AMD64 is intended to assist in the cross-compilation process, indicating the target operating system and architecture.
The go executable takes the form of a static link, so the actual runtime does not require additional target files.

Package names

The first statement of the go source file must be

package name

where name is the code package name (files in the same package should use the same name)
The tradition of Go is that the code package name should use the last element of the import path: for example, the import path name crypto/rot13 should be the package name rot13 .
The package name of the executable file always needs to be package main
There is no unique requirement for all dependent package names that are ultimately compiled into the same file, and only the full import path (including the package name) is unique.
For more go naming traditions, see effective go

Testing

The

Go comes with a lightweight test framework consisting of the go Test command and the testing package.
You can create a test file with a suffix of _test.go that contains the type func (t *testing) named testxxx . T) The method. The test framework will run all of these methods. If the method calls an error prompt method that resembles t.error and T.fail in the run, it means that the test method test failed.
Add a test function to stringutil code package $GOPATH/src/github.com/user/stringutil/reverse_test.go :

package  stringutilimport   "testing"  func testreverse (t *testing. T) {cases: = []struct  {in , want string } {{ "Hello, World" ,  " Dlrow, Olleh "}, {" Hello, World ", " world, Olleh "} , {, },} fo R  _, c: = Range Cases {got: = Reverse (C.in ) if  got! = c.want {T.errorf (" Reverse (%q) = =%q, want%q ", C.in , Got, C.want)}}} 

Then use the Go Test command to run the test:

$ go test github.com/user/stringutilok      github.com0.165s

As mentioned before, if you are in the directory where the code package is located, you can also run the following directly

$ go testok      0.165s

Run go help test and see the testing package documentation for more assistance with the test framework

Remote Packages

The import path shows how the version control system (git or mercurial, etc.) can get the corresponding code package. The Go tool uses this to automatically get the corresponding code package from the remote repository. For example, our sample code is saved on GitHub github.com/golang/example. If you use such an import path in your source code,go get will be able to get, compile, and install it automatically:

$ go get github.com/golang/example/hello$ $GOPATH/bin/helloHelloGo examples!

If the current workspace does not contain an imported package, thego get command will place him in the first path of Gopath (if obtained, go get skips the get phase, just like running go install)
After running the go get command above, our workspace should already look like this:

Bin/hello# command ExecutablePkg/linux_amd64/github. com/golang/example/stringutil. A            # Package ObjectGitHub. com/user/stringutil. A            # Package ObjectSrc/github. com/golang/example/. Git/# Git Repository metadataHello/hello. Go                # command SourceStringutil/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 on GitHub relies on the Stringutil code package for the same repository. The import path used in the Hello.go file follows the same rules, so go get also pulls the dependent code package down

import"github.com/golang/example/stringutil"

This is the simplest way to get your code package to be reused by others. Some third-place go codes are listed on the Go Wiki and godoc.org.
For more ways to use the go tool 's remote repository, see go help Importpath

What ' s Next

Subscribe to the Golang-announce mailing list to being notified when a new stable version of Go is released.
See effective go for tips on writing clear, idiomatic go code.
Take A tour of Go to learn the language proper.
Visit the documentation page for a set of in-depth articles about the Go language and its libraries and tools.

Getting Help

For real-time help, ask the helpful gophers in #go-nuts on the freenode IRC server.
The official mailing list for discussion of the go language is go Nuts.
Report bugs using the 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.