Iteration
To do stuff repeatedly in Go, you’ll need . In Go there are no while
, do
, until
keywords, you can only use for
. Which is a good thing!
Let’s write a test for a function that repeats a character 5 times.
There’s nothing new so far, so try and write it yourself for practice.
Try and run the test
./repeat_test.go:6:14: undefined: Repeat
Keep the discipline! You don’t need to know anything new right now to make the test fail properly.
All you need to do right now is enough to make it compile so you can check your test is written well.
package iteration
return ""
}
repeat_test.go:10: expected 'aaaaa' but got ''
Write enough code to make it pass
The syntax is very unremarkable and follows most C-like languages.
Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for statement and the braces { } are always required.
Run the test and it should pass.
Additional variants of the for loop are described here.
Now it’s time to refactor and introduce another construct +=
assignment operator.
const repeatCount = 5
func Repeat(character string) string {
var repeated string
for i := 0; i < repeatCount; i++ {
repeated += character
}
return repeated
Writing in Go is another first-class feature of the language and it is very similar to writing tests.
You’ll see the code is very similar to a test.
The gives you access to the cryptically named b.N
.
When the benchmark code is executed, it runs b.N
times and measures how long it takes.
The amount of times the code is run shouldn’t matter to you, the framework will determine what is a “good” value for that to let you have some decent results.
To run the benchmarks do go test -bench=.
(or if you’re in Windows Powershell go test -bench="."
)
goos: darwin
goarch: amd64
pkg: github.com/quii/learn-go-with-tests/for/v4
10000000 136 ns/op
PASS
NOTE by default Benchmarks are run sequentially.
Practice exercises
- Change the test so a caller can specify how many times the character is repeated and then fix the code
- Write
ExampleRepeat
to document your function - Have a look through the package. Find functions you think could be useful and experiment with them by writing tests like we have here. Investing time learning the standard library will really pay off over time.
- More TDD practice
- Learned