3 min read

Iteration in Go with Tests

Table of Contents

Hey there! 👋 Today, we’re tackling iteration in Go—aka how to do things over and over without losing your sanity.

Good news: Go keeps it simple. No while, do, or until—just for. Less syntax, fewer headaches.

Let’s Write a Test First

We’ll make a function that repeats a character 5 times. Here’s the test:

package iteration

import "testing"

func TestRepeat(t *testing.T) {
	repeated := Repeat("a")
	expected := "aaaaa"

	if repeated != expected {
		t.Errorf("expected %q but got %q", expected, repeated)
	}
}

Running this gives us:

./repeat_test.go:6:14: undefined: Repeat

Classic. Time to write just enough code to fail properly.

Make It Compile (Then Fail)

package iteration

func Repeat(character string) string {
	return ""
}

Now the test fails like a good little test should:

repeat_test.go:10: expected 'aaaaa' but got ''

Write the Real Code

Here’s how for works in Go—clean and simple:

func Repeat(character string) string {
	var repeated string
	for i := 0; i < 5; i++ {
		repeated += character
	}
	return repeated
}

No parentheses around the loop conditions (thanks, Go!), and braces are mandatory. Also, meet +=, the “add-and-assign” operator. It’s like a lazy programmer’s best friend.

Refactor Like a Pro

Let’s avoid magic numbers and use a constant:

const repeatCount = 5

func Repeat(character string) string {
	var repeated string
	for i := 0; i < repeatCount; i++ {
		repeated += character
	}
	return repeated
}

Benchmarking: Because Speed Matters

Want to know how fast your code is? Go’s got you covered.

func BenchmarkRepeat(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Repeat("a")
	}
}

Run it with:

go test -bench=.

Output:

10000000           136 ns/op

That’s 136 nanoseconds per operation. Not bad!

Optimizing with strings.Builder

Concatenating strings in Go isn’t free—each += copies memory. For heavy lifting, use strings.Builder:

func Repeat(character string) string {
	var builder strings.Builder
	for i := 0; i < repeatCount; i++ {
		builder.WriteString(character)
	}
	return builder.String()
}

Now benchmark again with -benchmem:

10000000           25.70 ns/op           8 B/op           1 allocs/op

25.7 ns/op—way faster! 🚀

Key Takeaways

  • ✅ More TDD practice
  • ✅ Learned for loops (the only loop you’ll ever need in Go)
  • ✅ Wrote benchmarks like a performance guru

Next Up: Arrays and Slices — because sometimes one variable just isn’t enough.

Support my open source work 🚀

Let's Connect

I'm open to discussing new opportunities. Feel free to connect with me or send me an email at [email protected]