Go?Go!(四) Go command的使用

本篇文档应该是第一篇文档的补充,笔者还还不是特别了解Go的使用的时候就盲目的去做安装和学习,绝对是一个失败的案例。。。

对于一般情况,使用Go只需要安装Go即可,不需要gccgo的安装,那个真的很慢,而且有一个最大的问题是没有go的支持。

go是一个有点强大的工具,可以安装包,测试包,从网上下载并安装包,还有一些附带的小工具,objdump什么的,都很好用。

对于go的使用,可以参照文档:http://golang.org/doc/code.html

在这里就不再翻译了,强调一下go test的使用即可。这个真心强大。


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.gothat contains functions named TestXXX with signaturefunc (t *testing.T). The test framework runs each such function; if the function calls a failure function such as t.Error ort.Fail, the test is considered to have failed.

写好一个code文件之后,以文件名+_test.go作为后缀,在test的文件中,包含需要测试的包的名字,导入测试的包。并且按照Test+FunctionName的命名方式命名测试函数。该函数的参数为 t *testing.T。 

Add a test to the newmath package by creating the file $GOPATH/src/example/newmath/sqrt_test.go containing the following Go code.

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

Now run the test with go test:

$ go test example/newmath
ok  	example/newmath 0.165s

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


这样一键式测试的功能真的很不错,能够保证每一个file,每一个函数的正确性(不从包中导出的函数无法测试?待确定)。

经过测试,私有函数也是可以测试的:

测试代码如下:

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

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


包的代码如下:
package newmath
// Sqrt returns an approximation to the square root of x.
func Sqrt(x float64) float64 {
    return privateSqrt(x);                                                                                                                   
}


func privateSqrt(x float64) float64{
    // This is a terrible implementation.
    // Real code should import "math" and use math.Sqrt.
    z := 0.0
    for i := 0; i < 1000; i++ {
       z -= (z*z - x) / (2 * x)
    }
    return z
}

要养成良好的习惯,保证每一个文件都有良好的测试。

Go Go Go



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值