Start writing Golang code

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

Introduced

This article focuses on how to write a simple go package and how to use Golang tools, how to get, compile, and install the go package, and how to use the GO command.

The tools of go need to organize the code in a certain way. So please read this article carefully.

Organization of the Code

Workspace

The Go tool is an open source code designed to handle a public code base, although you don't have to expose your code, but the pattern of work is the same.

The go code must be saved in a workspace. A workspace must contain three subdirectories in the root directory:
* src contains the source files for go, which are present in the form of the package
* PKG contains the package object
* Bin contains executable files

The Go tool compiles the source files and stores the compiled binaries in the pkg and bin directories.

The following is a typical Go project directory:

Bin/hello# command executable outyet # command executable pkg/ Linux_amd64/github.com/golang/example/stringutil.a # package object Src/github.com/golang/ex ample/.git/hello/hello.go # source file Outyet/main.go # source file Main_ Test.go # test source file Stringutil/reverse.go # source file Reverse_test.go # test source file            

This workspace contains only a code base ( example ), which contains two packages hello and outyet a library stringutil .

A typical workspace can contain multiple code libraries, as well as multiple packages and libraries in each library. Most go developers put these in a separate workspace.

Packages and libraries are compiled from different source file packages. We will discuss this later.

Gopath Environment variables

GOPATHThe environment variable specifies the location of your workspace. This is probably the only environment variable that you need to set when you develop a go project.

Create a workspace directory before you begin, and then specify the location of this workspace directory in Gopath. You can assign Gopath to any location you like.
However, this article uses $home/work as the location of the workspace directory. Note that this directory must not be the same as your go installation directory .

$ mkdir $HOME/work$ export GOPATH=$HOME/work

Then add the workspace Bin directory to the path.

export PATH=$PATH:$GOPATH/bin

Package path

The package path for the standard library will be abbreviated: "fmt" and "net/http" . You need to choose a path for your own package. Because, you don't want to later and standard library packages or other
The names of the packages used conflict with each other.

If you save your code in a code base, you should use the root of the codebase as a directory:

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

# # #你的第一个程序
To compile, run your program, first select a package path (we will use it github.com/user/hello ) and create a corresponding package path in your workspace

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

Then, create a Hello.go file. and add the following code to this file:
"' Go
Package Main

Import "FMT"

Func Main () {
Fmt. Println ("Hello, world!")
}
"'

Now you can compile and run your code:

go install github.com/user/hello 

Note that you can run this command from anywhere on your system. Go tool can github.com/user/hello find source files from workspace according to Gopath

Once the above command line executes, a self-workspace file is generated in the bin directory of the "Hello" (or hello.exe under Windows). In our
The directory in the example is: $GOPATH/bin/hello .

The Go tool will only print out information when an error occurs. So, if there is no information to print, then it is compiled successfully.

Now you can run your program:

$ $GOPATH/bin/hello 
Hello, world! 

Or, you have added the path GOPATH/bin , just enter the name of the executable file:

$ helloHello, world!

If you use the Code management tool, you can initialize a code base. Add a file, and commit your first change. However, this is not a must, but
You can write go code without the Code tool.

$ cd $GOPATH/src/github.com/user/hello$ git initInitialized empty Git respository in /home/user/work/src/github.com/user/hello/.git/$ git add hello.go$ git commit -m "initial commit"[master (root-commit) 0b4507d] initial commit 1 file changed, 1 insertion(+) create mode 100644 hello.go

Publish the code to the remote code base so that other readers can see your code.

Your first library

Next, we create a library and then use the library in the Hello code.

In common sense we need to select a package path (we use github.com/user/stringutil here) and create the package path

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

Then, wear a file:reverse.go, the content is:

package stringutilfunc Reverse(s string) string {    var 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)}

Now, use the go build command to test if the code compiles.

$ go build github.com/user/stringutil

Or if you're under the path of this package, you just need to:

$ go build

This does not generate any files. To generate a file, you must use it go install . After executing this command, the package is compiled and generated in the PKG directory.
After Stringutil compilation, modify the code for HELLO.GO:

package mainimport (    "fmt"    "github.com/user/stringutil")func main() { fmt.Println(stringutil.Reverse("!oG ,olleH"))}

Any time a go tool installs a package or a binary file, its dependencies will be installed together. So, when you install hello :

$ go install github.com/user/hello

stringutilThe package will also be installed automatically .

Run the new version of the program and you will see a new, reversed message:

$ helloHello, Go!

After the above steps are complete, your directory looks like this:

bin/    hellopkg/    linux_amd64/        github.com/user/            stringutil.asrc/    github.com/user/        hello/            hello.go        stringutil/            reverse.go

Note that the go install stringutil.a is placed in the pkg/linux_amd64 directory and will be created under linux_amd64 with the same structure as the directory where the source files are located.
In the compilation after the Go tool, if this file is found in the PKG, it will not be compiled again. This avoids unnecessary duplication of compilation. linux_amd64 directory is for cross-compiling
and reflects the operating system and system architecture in which it resides.

The executable file for Go is statically linked.

Package Name

The first line of the go source file must be:

package name

The package name is the default name used when import, and the files in the same package must use the same package name.

The Convention of Go is that the package name is the last element of the import statement. crypto/rot13The package that is introduced should be named rot13 .
mainThe package that contains the function must be used package main as the package name.

The package name does not have to be unique, but the entire introduction path for the report must be unique.

Test

Go has a lightweight test framework consisting of a go test testing bundle of packages.

Write a test only, create a _test.go end of the file, this file contains a method called Testxxx, the signature of these test methods is func (T *testing. T).
The test framework runs every one of these methods. If a test method calls T. Error or T.fail, then this test is considered to be a failure.

Add a test to stringutil. Create the file Reverse_test.go in the $gopath/src/github.com/user/sringutil/directory. This file contains
The following code:

package Stringutilimport  "testing" func Testreverse (t *testing. T) {case: = []struct {in, want str ing} {{ "Hello, World",  "Dlrow, Olleh"}, {  "Hello, World", for _, c: = range cases {got: = Reverse (c.in) if got! = c.want{T.errorf ( "Reverse (%q) = =%q", c.in, got, C . Want)}}}                

Then use the command go test to run the test:

$ go test github.com/user/stringutilPASSok          stringutil          2.223s  

You can save the package path if you run the command internally.

$ go testPASSok          stringutil          2.223s

Run go help test the command to see more details about the test command.

Remote packages Remote code base

An import path is the same as the path to get remote code using GIT. The Go tool uses this path to automatically get the code from the remote code base. For example, the code used above
The path hosted on GitHub is: github.com/golang/example . If the remote code is included in the import statement of the code, the go get command automatically gets, compiles
and install the code.

$ go get github.com/golang/example/hello$ $GOPATH/bin/helloHello, Go examples!

If the required package is not in workspace, the go get command places the packages in the first workspace specified by Gopath . If the package already exists, then go get
command skips a remote fetch and executes go install a similar command directly.

After executing the above go get command, the workspace directory looks like this:

bin/hellopkg/linux_amd64/gith Ub.com/golang/example/stringutil.a gith Ub.com/user/stringutil.asrc/github.com/golang/example/.git/hello/hello.a stringutil/reverse.go reverse_test .go github.com/user/hello/hello.go stringutil/reverse.go reverse_test.go             

The hello hosted on GitHub relies on the same package stringutil . The hello.go import statement in is using the same convention . So the go get command
You can locate and install a dependent package.

import "github.com/golang/example/stringutil

This practice will make your code very easy for others to use.

Next...

Effective Go has more information about writing go code effectively.

A tour of Go has more knowledge about go.

Get help

Come here to discuss the go language in the official mailing list.

Here go Issue Tracker to submit the bug.



Original

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.