How to Write Go Code   如何编写go语言代码

Introduction   介绍
Code organization  组织代码
Overview  概述
Workspaces  工作区
The GOPATH environment variable GOPATH环境变量
Import paths 导入路径
Your first program  你的第一个程序
Your first library 您的第一个库
Package names  包名字
Testing  测试
Remote packages 远程包
What's next  下一个
Getting help  帮助
 

Introduction 介绍

This document demonstrates the development of a simple Go package and introduces the go tool, the standard way to fetch, build, and install Go packages and commands.

The go tool requires you to organize your code in a specific way. Please read this document carefully. It explains the simplest way to get up and running with your Go installation.

A similar explanation is available as a screencast.

本文档说明了一个简单的go包和go工具的接口,获取、生成的标准方法,安装go包和命令行。go工具需要你用特殊的方式组织你的代码,请认真阅读这份文档。它解释了用最简单的方式来获取和运行你安装的go。

Code organization 组织代码

Overview  概述

  • Go programmers typically keep all their Go code in a single workspace. go语言项目通常保存在一个单独的工作区中。
  • A workspace contains many version control repositories (managed by Git, for example). 工作区包含许多版本控制存储库 (例如, 由 Git 管理)。
  • Each repository contains one or more packages. 每个存储库都包含一个或者更多的包。
  • Each package consists of one or more Go source files in a single directory.每个包由一个或者多个go语言源码文件在单独的文件夹中组成。
  • The path to a package's directory determines its import path. 包目录的路径决定了它的导入路径。

Note that this differs from other programming environments in which every project has a separate workspace and workspaces are closely tied to version control repositories. 请注意, 这与其他编程环境不同, 其中每个项目都有一个单独的工作区, 工作区与版本控制存储库紧密相连。

Workspaces 工作区

A workspace is a directory hierarchy with two directories at its root: 工作区是目录层次结构, 其根目录有两个:

  • src contains Go source files, and        src包含go源码文件
  • bin contains executable commands.    bin包含可执行命令

The go tool builds and installs binaries to the bin directory.   bin文件夹是go工具构建和安装二进制文件的地方。

The src subdirectory typically contains multiple version control repositories (such as for Git or Mercurial) that track the development of one or more source packages.   src的子目录通常包含用于跟踪一个或多个源包开发的多个版本控制存储库 (如 Git 或 Mercurial)。

To give you an idea of how a workspace looks in practice, here's an example: 为了让您了解工作区在实践中的外观, 下面是一个示例:

bin/
hello # command executable
outyet # command executable
src/
github.com/golang/example/
.git/ # Git repository metadata
hello/
hello.go # command source
outyet/
main.go # command source
main_test.go # test source
stringutil/
reverse.go # package source
reverse_test.go # test source
golang.org/x/image/
.git/ # Git repository metadata
bmp/
reader.go # package source
writer.go # package source
... (many more repositories and packages omitted) ...

The tree above shows a workspace containing two repositories (example and image). The example repository contains two commands (hello and outyet) and one library (stringutil). The image repository contains the bmp package and several others.

A typical workspace contains many source repositories containing many packages and commands. Most Go programmers keep all their Go source code and dependencies in a single workspace.

Note that symbolic links should not be used to link files or directories into your workspace.

Commands and libraries are built from different kinds of source packages. We will discuss the distinction later.

The GOPATH environment variable  GOPATH环境变量

The GOPATH environment variable specifies the location of your workspace. It defaults to a directory named goinside your home directory, so $HOME/go on Unix, $home/go on Plan 9, and %USERPROFILE%\go (usually C:\Users\YourName\go) on Windows.

If you would like to work in a different location, you will need to set GOPATH to the path to that directory. (Another common setup is to set GOPATH=$HOME.) Note that GOPATH must not be the same path as your Go installation.

The command go env GOPATH prints the effective current GOPATH; it prints the default location if the environment variable is unset.

For convenience, add the workspace's bin subdirectory to your PATH:

$ export PATH=$PATH:$(go env GOPATH)/bin

The scripts in the rest of this document use $GOPATH instead of $(go env GOPATH) for brevity. To make the scripts run as written if you have not set GOPATH, you can substitute $HOME/go in those commands or else run:

$ export GOPATH=$(go env GOPATH)

To learn more about the GOPATH environment variable, see 'go help gopath'.

To use a custom workspace location, set the GOPATH environment variable.

Import paths  导入包

An import path is a string that uniquely identifies a package. A package's import path corresponds to its location inside a workspace or in a remote repository (explained below).

The packages from the standard library are given short import paths such as "fmt" and "net/http". For your own packages, you must choose a base path that is unlikely to collide with future additions to the standard library or other external libraries.

If you keep your code in a source repository somewhere, then you should use the root of that source repository as your base path. For instance, if you have a GitHub account at github.com/user, that should be your base path.

Note that you don't need to publish your code to a remote repository before you can build it. It's just a good habit to organize your code as if you will publish it someday. In practice you can choose any arbitrary path name, as long as it is unique to the standard library and greater Go ecosystem.

We'll use github.com/user as our base path. Create a directory inside your workspace in which to keep source code:

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

Your first program  你的第一个程序

To compile and run a simple program, first choose a package path (we'll use github.com/user/hello) and create a corresponding package directory inside your workspace:

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

Next, create a file named hello.go inside that directory, containing the following Go code.

package main

import "fmt"

func main() {
fmt.Println("Hello, world.")
}

Now you can build and install that program with the go tool:

$ go install github.com/user/hello

Note that you can run this command from anywhere on your system. The go tool finds the source code by looking for the github.com/user/hello package inside the workspace specified by GOPATH.

You can also omit the package path if you run go install from the package directory:

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

This command builds the hello command, producing an executable binary. It then installs that binary to the workspace's bin directory as hello (or, under Windows, hello.exe). In our example, that will be $GOPATH/bin/hello, which is $HOME/go/bin/hello.

The go tool will only print output when an error occurs, so if these commands produce no output they have executed successfully.

You can now run the program by typing its full path at the command line:

$ $GOPATH/bin/hello
Hello, world.

Or, as you have added $GOPATH/bin to your PATH, just type the binary name:

$ hello
Hello, world.

If you're using a source control system, now would be a good time to initialize a repository, add the files, and commit your first change. Again, this step is optional: you do not need to use source control to write Go code.

$ cd $GOPATH/src/github.com/user/hello
$ git init
Initialized empty Git repository 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

Pushing the code to a remote repository is left as an exercise for the reader.

Your first library  你的第一个库

Let's write a library and use it from the hello program.

Again, the first step is to choose a package path (we'll use github.com/user/stringutil) and create the package directory:

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

Next, create a file named reverse.go in that directory with the following contents.

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

Now, test that the package compiles with go build:

$ go build github.com/user/stringutil

Or, if you are working in the package's source directory, just:

$ go build

This won't produce an output file. Instead it saves the compiled package in the local build cache.

After confirming that the stringutil package builds, modify your original hello.go (which is in$GOPATH/src/github.com/user/hello) to use it:

package main

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

Install the hello program:

$ go install github.com/user/hello

Running the new version of the program, you should see a new, reversed message:

$ hello
Hello, Go!

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

bin/
hello # command executable
src/
github.com/user/
hello/
hello.go # command source
stringutil/
reverse.go # package source

Package names 包名

The first statement in a Go source file must be

package name

where name is the package's default name for imports. (All files in a package must use the same name.)

Go's convention is that the package name is the last element of the import path: the package imported as "crypto/rot13" should be named rot13.

Executable commands must always use package main.

There is no requirement that package names be unique across all packages linked into a single binary, only that the import paths (their full file names) be unique.

See Effective Go to learn more about Go's naming conventions.

Testing  测试

Go has a lightweight test framework composed of the go test command and the testing package.

You write a test by creating a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T). The test framework runs each such function; if the function calls a failure function such as t.Error or t.Fail, the test is considered to have failed.

Add a test to the stringutil package by creating the file$GOPATH/src/github.com/user/stringutil/reverse_test.go containing the following Go code.

package stringutil

import "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)
}
}
}

Then run the test with go test:

$ go test github.com/user/stringutil
ok github.com/user/stringutil 0.165s

As always, if you are running the go tool from the package directory, you can omit the package path:

$ go test
ok github.com/user/stringutil 0.165s

Run go help test and see the testing package documentation for more detail.

Remote packages 远程包

An import path can describe how to obtain the package source code using a revision control system such as Git or Mercurial. The go tool uses this property to automatically fetch packages from remote repositories. For instance, the examples described in this document are also kept in a Git repository hosted at GitHubgithub.com/golang/example. If you include the repository URL in the package's import path, go get will fetch, build, and install it automatically:

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

If the specified package is not present in a workspace, go get will place it inside the first workspace specified by GOPATH. (If the package does already exist, go get skips the remote fetch and behaves the same as go install.)

After issuing the above go get command, the workspace directory tree should now look like this:

bin/
hello # command executable
src/
github.com/golang/example/
.git/ # Git repository metadata
hello/
hello.go # command source
stringutil/
reverse.go # package source
reverse_test.go # test source
github.com/user/
hello/
hello.go # command source
stringutil/
reverse.go # package source
reverse_test.go # test source

The hello command hosted at GitHub depends on the stringutil package within the same repository. The imports in hello.go file use the same import path convention, so the go get command is able to locate and install the dependent package, too.

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

This convention is the easiest way to make your Go packages available for others to use. The Go Wiki and godoc.org provide lists of external Go projects.

For more information on using remote repositories with the go tool, see go help importpath.

What's next 下一个

Subscribe to the golang-announce mailing list to be 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.

02 How to Write Go Code 如何编写go语言代码的更多相关文章

  1. VS Code中编写C

    Visual Studio Code如何编写运行C.C++? Visual Studio Code的C/C++扩展功能 vscode配置C/C++的编译调试环境

  2. Visual Studio Code 如何编写运行 C、C++ 程序?

    0. 前言 VS Code 是微软发布一款跨平台的源代码编辑器,其拥有强大的功能和丰富的扩展,使之能适合编写许多语言. 本文面向初学者(但不是纯小白),分享一点我配置C/C++的经验. 本文所有内容均 ...

  3. Visual Studio Code如何编写运行C、C++

    Visual Studio Code如何编写运行C.C++ 作者:知乎用户链接:https://www.zhihu.com/question/30315894/answer/154979413来源:知 ...

  4. 在VS Code中编写IAR项目

    在VS Code中编写IAR项目 首先按照网上的教程,下载C/C++插件,以及IAR Eebedded Workbench插件,安装完成重启VS Code. 项目目录下新建.vscode文件夹,并新建 ...

  5. 编写高质量代码的50条黄金守则-Day 02(首选readonly而不是const)

    编写高质量代码的50条黄金守则-Day 02(首选readonly而不是const),本文由比特飞原创发布,转载务必在文章开头附带链接:https://www.byteflying.com/archi ...

  6. 编写高质量代码--改善python程序的建议(六)

    原文发表在我的博客主页,转载请注明出处! 建议二十八:区别对待可变对象和不可变对象 python中一切皆对象,每一个对象都有一个唯一的标识符(id()).类型(type())以及值,对象根据其值能否修 ...

  7. 编写高质量代码:改善Java程序的151个建议(第二章:基本类型)

    编写高质量代码:改善Java程序的151个建议(第二章:基本类型) 目录 建议21:用偶判断,不用奇判断 建议22:用整数类型处理货币 建议23:不要让类型默默转换 建议24:边界还是边界 建议25: ...

  8. Visual Studio Code(VSCODE)语言设置

    Visual Studio Code(VSCODE)语言设置 语言设置 1.快捷键 Windows.Linux 快捷键是:ctrl+shift+p macOS 快捷键是:command + shift ...

  9. 编写高质量代码改善java程序的151个建议——[1-3]基础?亦是基础

    原创地址:   http://www.cnblogs.com/Alandre/  (泥沙砖瓦浆木匠),需要转载的,保留下! Thanks The reasonable man adapts himse ...

随机推荐

  1. Xcode一个project生成多个App

    网上有很多奇奇怪怪的复杂的方案,其实误导了,方法很简单: 打开项目属性 修改Bundle Identifiler 随便生成了四个App,如下所示:

  2. 阿里大鱼短信发送,放到项目中报错Java.lang.NoClassDefFoundError:com/aliyuncs/exceptions/ClientException,已解决

    由于项目中使用的短信服务发送的消息太慢,所以把采用了阿里大鱼的短信服务,花费了几个小时,通过审核,发现可以单独运行.但是,放到web项目中会报错(Java.lang.NoClassDefFoundEr ...

  3. 【Learning】分数规划

    分数规划 ​ 分数规划是一类决策性问题.一般地,题目会要求你针对问题规划一种方案,使得其代价函数最小或最大.其中,代价函数一般是分数形式,且分子分母的构成元素一般呈现一一对应关系. 直接上例题观察:B ...

  4. Nginx web服务优化 (一)

    1.Nginx基本安全优化 a.更改配置文件参数隐藏版本 编辑nginx.conf配置文件增加参数,实现隐藏Nginx版本号的方式如下.在nginx配置文件nginx.conf中的http标签段内加入 ...

  5. Linux使用vim进行多文件查找和替换的方法

    vim是Linux系统下常用的文本编辑,通过使用多种shell命令能够实现多文件的查找和替换,那么具体会使用到那些命令呢?下面小编就给大家介绍下Linux系统vim多文件查找和替换的方法. 在linu ...

  6. lumen 使用 dingo API 在 phpunit 中 404 的解决方法, 以及鉴权问题

    1. phpunit.xml 中添加 dingo 相关配置 <env name="API_STANDARDS_TREE" value="x"/> & ...

  7. UVAL 7902 2016ECfinal F - Mr. Panda and Fantastic Beasts

    题意: 给出n个串,求一个最短的第一个串的子串使它不在其他的n-1个串中出现,若有多个求字典序最小的. Limits: • 1 ≤ T ≤ 42. • 2 ≤ N ≤ 50000. • N ≤ S1 ...

  8. Unity官方实例教程 Roll-a-Ball

    与unity的transform组件相处的挺久了,最近项目不太忙,决定好好打下unity的基础.那么从Roll-a-Ball这个简单游戏开始吧! 1.先创建一个球体游戏对象,改名为Player,tra ...

  9. ip地址、子网掩码、DNS的关系与区别

    首先ip地址可能表示内网或者外网地址: 内网也就是局域网,最直观的就是像网吧,公司内部的电脑用交换机,HUB,路由连起来的.再通过光钎.猫接入INTERNET的. 外网就像你家里的一台电脑.用猫拨号上 ...

  10. 在升级Windows 8.1后,桌面的右下角显示"SecureBoot未正确配置"

    原地址为:http://ask.zol.com.cn/q/201881.html 第一种模式BIOS: 在将Secure Boot设置为Enabled后,Secure Boot Status依然为关闭 ...