3 min read

Integers in Go with Tests

Table of Contents

Hey there! 👋 Ready to dive into Go’s integers?

Don’t worry – I’ll make this as painless as possible. Maybe even fun! (Okay, maybe not that fun, but definitely understandable.)

Let’s Add Some Numbers! ➕

First things first – we’re going to create a simple Add function. But being good developers, we’ll test it first. Because that’s what cool kids do these days. 😎

Step 1: Write the Test (Yes, Before the Code!)

Create adder_test.go and throw in this:

package integers

import "testing"

func TestAdder(t *testing.T) {
    sum := Add(2, 2)
    expected := 4

    if sum != expected {
        t.Errorf("Oops! Expected '%d' but got '%d'", expected, sum)
    }
}

Notice we’re using %d here because we’re dealing with integers, not strings.

Step 2: Watch It Fail (It’s Part of the Process!)

Run go test and… boom! 💥

./adder_test.go:6:9: undefined: Add

The compiler’s basically saying: “Add? What Add? I don’t know her.”

Let’s fix that.

Step 3: Write Just Enough Code to Fail Better

package integers

func Add(x, y int) int {
    return 0 // The laziest implementation possible
}

Run the test again:

adder_test.go:10: expected '4' but got '0'

Perfect! Our test is failing for the right reason now.

Step 4: Make It Pass (For Real This Time)

func Add(x, y int) int {
    return x + y // Math! It works!
}

Run the tests… and voilà! 🎉 All green. You’re officially a Go adder now.

Let’s Make It Shine ✨

Add Some Docs (Because Future You Will Thank Present You)

// Add takes two integers and returns their sum.
// (Yes, it's that simple. No hidden fees.)
func Add(x, y int) int {
    return x + y
}

Bonus: Testable Examples (Fancy!)

Want to show off your function in the docs? Add this to adder_test.go:

func ExampleAdd() {
    sum := Add(1, 5)
    fmt.Println(sum)
    // Output: 6
}

Now when someone looks at your package docs, they’ll see a working example.

And if the example stops working, your tests will catch it!

What We Learned Today 🎓

  • 🧪 More TDD practice (Write test → See fail → Make pass → Repeat)
  • 📖 Better documentation (Your future self sends their thanks)
  • 🎁 Testable examples (Documentation that never lies!)

Next Up: Iteration.

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]