Golang极简入门教程(四):编写第一个项目

2019-11-10 09:01:12王冬梅

另外需要注意的是,Golang 使用静态链接(运行 Go 程序无需包对象)。

测试

Golang 带有轻量级测试框架,主要包括:

1.go test 命令
2.testing 包

创建文件 _test.go 来编写测试,例如为 sqrt.go 创建的测试文件为 sqrt_test.go:


package newmath
 
import "testing"
 
func TestSqrt(t *testing.T) {
    const in, out = 4, 2
    if x := Sqrt(in); x != out {
        t.Errorf("Sqrt(%v) = %v, want %v", in, x, out)
    }
}

执行测试使用 go test:


go test github.com/name5566/newmath

测试文件中包含的所有测试函数 func TestXxx(t *testing.T) 都会被执行。测试函数可以通过 Error、Fail 等相关方法告知出现错误。

另外,在测试文件中还可以编写范例代码,例如:

func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}

这里 Example 函数结尾可以跟上一个以 “Output:” 字符串开始的注释(被叫做输出注释),在测试运行时会将 Example 函数输出注释中字符串和函数标准输出进行比对。需要注意的是,如果没有输出注释,Example 函数是不会被运行的(但是会被编译)。

Example 函数命名有这样的习惯:


func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }

这里的 F 为函数名,T 为类型名,T_M 为类型 T 上的方法 M。

获取远程仓库的包

使用 go get 能够自动获取远程仓库的包,例如:

go get code.google.com/p/go.example/hello