從測試中學習 Go 語言 (迴圈迭代篇)
Contents
Iteration
go 語法沒有 do , while 等關鍵字,所有的迴圈迭代只能用 for 去實現
For loop
|
|
While loop
|
|
Example
repeat_test.go
- 撰寫 Test function 與 Benchmark function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package repeat import "testing" func TestRepeat(t *testing.T) { repeated := Repeat("a") expected := "aaaaa" if repeated != expected { t.Errorf("expected %q but got %q", expected, repeated) } } func BenchmarkRepeat(b *testing.B) { for i := 0; i < b.N; i++ { Repeat("a") } }
repeat.go
1 2 3 4 5 6 7 8 9 10 11
package repeat const repeatCount = 5 func Repeat(character string) string { var repeated string for i := 0; i < repeatCount; i++ { repeated += character } return repeated }
test result
1 2 3 4 5 6 7 8 9 10 11 12 13 14
vscode ➜ /workspaces/learn-go/repeat $ go test -v === RUN TestRepeat --- PASS: TestRepeat (0.00s) PASS ok test-with-go/repeat 0.002s vscode ➜ /workspaces/learn-go/repeat $ go test -bench . goos: linux goarch: arm64 pkg: test-with-go/repeat BenchmarkRepeat-8 13891360 86.05 ns/op PASS ok test-with-go/repeat 1.288s