go官方一个非常精简的介绍Writing, building, installing, and testing Go code
Essential Go
看一遍视频跟着操作,记录命令执行过程,其中hello.go源码如下:

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

命令执行过程如下,主要演示了设置GOPATH,代码如何组织,生成的二进制文件,并且设置环境变量直接执行二进制:

[root 52coder]#mkdir -p /root/workspace/go
[root 52coder]#mkdir -p /root/workspace/go/src/github.com/52coder
[root 52coder]#export GOPATH=/root/workspace/go/
[root 52coder]#cd /root/workspace/go/src/github.com/52coder
[root 52coder]#mkdir hello
[root 52coder]#cd hello/
[root hello]#vi hello.go
[root hello]#go install
[root hello]#cd /root/workspace/go/bin/
[root bin]#ll
total 1976
drwxr-xr-x 2 root root    4096 Dec 20 10:58 ./
drwxr-xr-x 4 root root    4096 Feb 13  2020 ../
-rwxr-xr-x 1 root root 2011612 Dec 20 10:58 hello*
[root bin]#./hello
Hello,world
[root hello]#export PATH=$PATH:/root/workspace/go/bin
[root hello]#hello
Hello,world

下面的操作演示生成package string,然后修改上面的hello.go,调用string.Reverse函数翻转字符串。
string.go代码(b := []byte(s)不能处理unicode字符)

package string

func Reverse(s string) string {
    b := []rune(s)
    for i := 0;i < len(b)/2;i++{
        j := len(b) - i - 1
    b[i],b[j] = b[j],b[i]
    }
    return string(b)
}
[root 52coder]#pwd
/root/workspace/go/src/github.com/52coder
[root 52coder]#mkdir string
[root 52coder]#cd string
[root string]#vi string.go
[root string]#go build
[root string]#go install
[root string]#ls /root/workspace/go/pkg/linux_amd64/github.com/52coder/
string.a
[root string]#file /root/workspace/go/pkg/linux_amd64/github.com/52coder/string.a
/root/workspace/go/pkg/linux_amd64/github.com/52coder/string.a: current ar archive
[root string]#pwd
/root/workspace/go/src/github.com/52coder/string
[root string]#cd ../hello/
[root hello]#vi hello.go
[root hello]#pwd
/root/workspace/go/src/github.com/52coder/hello
[root hello]#vi hello.go
[root hello]#go run hello.go
dlrow,olleH
[root hello]#go install
[root hello]#hello
dlrow,olleH

下面的操作演示了单测的写法:

[root string]#pwd
/root/workspace/go/src/github.com/52coder/string
[root string]#
[root string]#vi string_test.go
[root string]#ll
total 12
drwxr-xr-x 2 root root 4096 Dec 20 11:23 ./
drwxr-xr-x 4 root root 4096 Dec 20 11:07 ../
-rw-r--r-- 1 root root  180 Dec 20 11:13 string.go
-rw-r--r-- 1 root root    0 Dec 20 11:23 string_test.go
[root string]#vi string_test.go
[root string]#
[root string]#go test
PASS
ok      github.com/52coder/string   0.001s

string_test.go源代码:

package string
import "testing"

func Test(t *testing.T) {
    var tests = []struct {
        s,want string
    }{
        {"Backward","drawkcaB"},
        {"Hello,世界","界世,olleH"},
        {"",""},
    }
    for _,c := range tests {
        got := Reverse(c.s)
    if got != c.want {
        t.Errorf("Reverse(%q) == %q,want %q",c.s,got,c.want)
    }
    }
}

至此完成了go的代码编写 打包 运行 测试等一系列操作。