This document should be a supplement to the first document. I am not familiar with Go installation and learning blindly, which is definitely a failure case...
In general, to use go, you only need to install go without installing gccgo. It is really slow, and the biggest problem is that it does not support go.
Go is a powerful tool. It can be used to install packages, test packages, download and install packages from the Internet, as well as some accompanying gadgets, such as objdump and so on.
For the use of go, see the document: http://golang.org/doc/code.html
I will not translate it here. I just need to emphasize the use of Go test. This is really powerful.
Testing
Go has a lightweight test framework composed ofgo test
Command andtesting
Package.
You write a test by creating a file with a name ending in_test.go
That contains functions namedTestXXX
With Signaturefunc
(t *testing.T)
. The test framework runs each such function; if the function CILS a failure function sucht.Error
Ort.Fail
,
The test is considered to have failed.
After a code file is written, the file name + _ test. Go is used as the suffix. In the test file, the file contains the name of the package to be tested and the package to be tested is imported. And name the test function according to the naming method of test + functionname. The parameter of this function is T * testing. T.
Add a test tonewmath
Package by creating the file$GOPATH/src/example/newmath/sqrt_test.go
Containing the following go code.
package newmathimport "testing"func TestSqrt(t *testing.T) {const in, out = 4, 2if x := Sqrt(in); x != out {t.Errorf("Sqrt(%v) = %v, want %v", in, x, out) }}
Now run the testgo test
:
$ go test example/newmathok example/newmath 0.165s
Rungo help test
And see thetesting
Package documentation for more detail.
In this way, the one-click test function is really good and can ensure the correctness of each file and function (the function exported from the package cannot be tested? To be determined ).
After testing, private functions can also be tested:
The test code is as follows:
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) } }
The package code is as follows:
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}
Develop good habits to ensure that every file has a good test.
Go go