How to write the Go code (how to write go codes translation)

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

Directory

    • 1. Write in the previous words
    • 2. Introduction
    • 3. Code organization
      • 3.1. Work area
      • 3.2. Gopath Environment variables
      • 3.3. Package path
      • 3.4. First GO Program
      • 3.5. First GO Library
      • 3.6. Package Name
    • 4. Testing
    • 5. Remote Package
    • 6. Next Step
    • 7. Get Help

Write it in front.

This article is the translation of the Go official website how to Write go Code this article,
The level is limited, some places are not good to translate the place to use the free translation method, regarding the code example path and so on aspect may also be somewhat different.

Introduced

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

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

Video reference for this article: https://www.youtube.com/watch?v=XCsL89YtqCs (Requires FQ!!!)

Code Organization

Work area

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: storing executable files

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 VC warehouses (such as Git or Mercurial) to manage code development.

The following is an example of a directory structure:

├── bin                                   # 这里存放 可执行命令├── pkg                                   # 这里存放 package 对象│   └── darwin_amd64│       ├── github.com│       └── go-files└── src    ├── github.com    │   └── golang    │       └── example    │           ├── .git    │           ├── hello               # 可执行命令的代码    │           ├── outyet              # 可执行命令的代码    │           └── stringutil          # package 代码    └── go-files        ├── .git        ├── hello                        # 可执行命令的代码        └── stringutil                   # package 代码

Here are some additional explanations:
SRC Directory:

    • Github.com/golang/example is a code warehouse on GitHub.
    • Go-files is the local code warehouse

The SRC directory can contain multiple code warehouses, can contain multiple command source code, or can contain multiple package source code.
Most go programmers keep all of their go source and dependencies in the same workspace.

Executable commands and libraries are compiled from different package code, and will be discussed later.

Gopath Environment variables

The GOPATH environment variable defines 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 variable.
Your workspace can be any folder, and the path used in this article is $HOME/go
Be careful not to set the Gopath to the Go installation path.

$ mkdir $HOME/go$ export GOPATH=$HOME/go

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

$ export PATH=$PATH:$GOPATH/bin

Package path

The package in the standard library can only be used with short paths, such as "FMT", "net/http".
For your own package, you must choose 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 in Github.com/user, you can use 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 code one day, it's a good practice to organize your code structure well.
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 Src/go-files as the base path and then create a folder in the workspace to save the code

$ mkdir -p $GOPATH/src/go-files

First GO Program

To compile and run a simple GO program, first determine the package path (using Go-files/hello here),
and create the corresponding package folder in the workspace.

$ mkdir $GOPATH/src/go-files/hello

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

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.

$ go install go-files/hello

You can run the above command from any path, and the Go tool will look for the Go-files/hello package 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.

$ cd $GOPATH/src/go-files/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/go/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.

$ $GOPATH/bin/hello

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

$ hello

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

$ cd $GOPATH/src/go-files/hello$ git init$ git add hello.go$ git commit -m "initial commit"

Publish this warehouse and make it a practice repository for readers.

First GO Library

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

$ mkdir $GOPATH/src/go-files/stringutil

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

// 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

$ go build go-files/stringutil

or in the package directory, run the go build directly

$ cd $GOPATH/src/go-files/stringutil$ 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:

package mainimport ( "fmt" "go-files/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,

$ go install go-files/hello

The Stringutil package will also be installed automatically.

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

$ helloHello, Go!

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

bin/    hello                 # command executablepkg/    darwin_amd64/          # this will reflect your OS and architecture        go-files/            stringutil.a  # package objectsrc/    go-files/        hello/            hello.go      # command source        stringutil/            reverse.go    # package source

Note that go install places STRINGUTIL.A in the Pkg/darwin_amd64 folder and in the directory that corresponds to the code.
Later, the Go tool can find the package to determine if it needs to be recompiled.
DARWIN_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 DARWIN_AMD64/GO-FILES/STRINGUTIL.A files when it is executed.

Package Name

The first line of the go code must be:

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)
The Go habit is that the 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 name of multiple package that is associated with a binary file 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's naming rules can be consulted: http://golang.org/doc/effective_go.html#names

Test

Go includes a lightweight test framework consisting of the Go Test command and the testing package.

The name of the test file ends with _test.go, which contains the format such as Func testxxxx (t *testing. T) of the function.
The test framework executes each of these functions, and if T.error or t.fail is called in the function, the test is considered to be unsuccessful.

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

package stringutilimport "testing"func TestReverse(t *testing.T) {  cases := []struct {      in, want string  }{      {"Hello, world", "dlrow ,olleH"},      {"Hello, 世界", "界世 ,olleH"},      {"", ""},  }  for _, c := range 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 perform the test:

$ go test go-files/stringutil

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

$ go test

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

Remote Package

The Go's import path can describe 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.

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

If the package for import is not specified locally, the go get command downloads the package to the first workspace defined in Gopath.
(Go get is equivalent to go install if the remote package does not exist)

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

├── bin│   └── hello├── pkg│   └── darwin_amd64│       ├── github.com│       │   └── golang│       │       └── example│       │           └── stringutil.a│       └── go-files└── src    ├── github.com    │   └── golang    │       └── example    │           ├── .git    │           ├── hello    │           │   └── hello.go    │           └── stringutil    │               ├── reverse.go    │               └── reverse_test.go    └── go-files        ├── hello        │   └── hello.go        └── stringutil            ├── reverse.go            └── reverse_test.go

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.

import (  "fmt"  "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.

Get 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.