Structs, methods & interfaces

    Suppose that we need some geometry code to calculate the perimeter of a rectangle given a height and width. We can write a function, where float64 is for floating-point numbers like 123.45.

    The TDD cycle should be pretty familiar to you by now.

    Notice the new format string? The f is for our float64 and the .2 means print 2 decimal places.

    Try to run the test

    ./shapes_test.go:6:9: undefined: Perimeter

    Write the minimal amount of code for the test to run and check the failing test output

    1. func Perimeter(width float64, height float64) float64 {
    2. return 0
    3. }

    Results in shapes_test.go:10: got 0 want 40.

    Write enough code to make it pass

    1. func Perimeter(width float64, height float64) float64 {
    2. return 2 * (width + height)
    3. }

    So far, so easy. Now let’s create a function called Area(width, height float64) which returns the area of a rectangle.

    Try to do it yourself, following the TDD cycle.

    You should end up with tests like this

    1. func TestPerimeter(t *testing.T) {
    2. got := Perimeter(10.0, 10.0)
    3. want := 40.0
    4. if got != want {
    5. t.Errorf("got %.2f want %.2f", got, want)
    6. }
    7. }
    8. func TestArea(t *testing.T) {
    9. got := Area(12.0, 6.0)
    10. want := 72.0
    11. if got != want {
    12. t.Errorf("got %.2f want %.2f", got, want)
    13. }
    14. }

    And code like this

    1. func Perimeter(width float64, height float64) float64 {
    2. return 2 * (width + height)
    3. }
    4. func Area(width float64, height float64) float64 {
    5. return width * height
    6. }

    Refactor

    Our code does the job, but it doesn’t contain anything explicit about rectangles. An unwary developer might try to supply the width and height of a triangle to these functions without realising they will return the wrong answer.

    We could just give the functions more specific names like RectangleArea. A neater solution is to define our own type called Rectangle which encapsulates this concept for us.

    We can create a simple type using a struct. A struct is just a named collection of fields where you can store data.

    Declare a struct like this

    1. type Rectangle struct {
    2. Width float64
    3. Height float64
    4. }

    Now lets refactor the tests to use Rectangle instead of plain float64s.

    1. func TestPerimeter(t *testing.T) {
    2. rectangle := Rectangle{10.0, 10.0}
    3. got := Perimeter(rectangle)
    4. want := 40.0
    5. if got != want {
    6. t.Errorf("got %.2f want %.2f", got, want)
    7. }
    8. }
    9. func TestArea(t *testing.T) {
    10. rectangle := Rectangle{12.0, 6.0}
    11. got := Area(rectangle)
    12. want := 72.0
    13. if got != want {
    14. t.Errorf("got %.2f want %.2f", got, want)
    15. }
    16. }

    Remember to run your tests before attempting to fix, you should get a helpful error like

    1. ./shapes_test.go:7:18: not enough arguments in call to Perimeter
    2. have (Rectangle)
    3. want (float64, float64)

    You can access the fields of a struct with the syntax of myStruct.field.

    Change the two functions to fix the test.

    1. func Perimeter(rectangle Rectangle) float64 {
    2. return 2 * (rectangle.Width + rectangle.Height)
    3. }
    4. func Area(rectangle Rectangle) float64 {
    5. return rectangle.Width * rectangle.Height

    I hope you’ll agree that passing a Rectangle to a function conveys our intent more clearly but there are more benefits of using structs that we will get on to.

    Our next requirement is to write an Area function for circles.

    Write the test first

    1. func TestArea(t *testing.T) {
    2. t.Run("rectangles", func(t *testing.T) {
    3. rectangle := Rectangle{12, 6}
    4. got := Area(rectangle)
    5. want := 72.0
    6. if got != want {
    7. t.Errorf("got %.2f want %.2f", got, want)
    8. }
    9. })
    10. t.Run("circles", func(t *testing.T) {
    11. circle := Circle{10}
    12. got := Area(circle)
    13. want := 314.1592653589793
    14. if got != want {
    15. t.Errorf("got %.2f want %.2f", got, want)
    16. }
    17. })
    18. }

    ./shapes_test.go:28:13: undefined: Circle

    Write the minimal amount of code for the test to run and check the failing test output

    We need to define our Circle type.

    Now try to run the tests again

    ./shapes_test.go:29:14: cannot use circle (type Circle) as type Rectangle in argument to Area

    Some programming languages allow you to do something like this:

    1. func Area(circle Circle) float64 { ... }
    2. func Area(rectangle Rectangle) float64 { ... }

    But you cannot in Go

    ./shapes.go:20:32: Area redeclared in this block

    We have two choices:

    • You can have functions with the same name declared in different packages. So we could create our Area(Circle) in a new package, but that feels overkill here.
    • We can define on our newly defined types instead.

    So far we have only been writing functions but we have been using some methods. When we call t.Errorf we are calling the method ErrorF on the instance of our t (testing.T).

    A method is a function with a receiver. A method declaration binds an identifier, the method name, to a method, and associates the method with the receiver’s base type.

    Methods are very similar to functions but they are called by invoking them on an instance of a particular type. Where you can just call functions wherever you like, such as Area(rectangle) you can only call methods on “things”.

    1. func TestArea(t *testing.T) {
    2. t.Run("rectangles", func(t *testing.T) {
    3. rectangle := Rectangle{12, 6}
    4. got := rectangle.Area()
    5. want := 72.0
    6. if got != want {
    7. t.Errorf("got %.2f want %.2f", got, want)
    8. }
    9. })
    10. t.Run("circles", func(t *testing.T) {
    11. circle := Circle{10}
    12. got := circle.Area()
    13. want := 314.1592653589793
    14. if got != want {
    15. t.Errorf("got %f want %f", got, want)
    16. }
    17. })
    18. }

    If we try to run the tests, we get

    1. ./shapes_test.go:19:19: rectangle.Area undefined (type Rectangle has no field or method Area)
    2. ./shapes_test.go:29:16: circle.Area undefined (type Circle has no field or method Area)

    I would like to reiterate how great the compiler is here. It is so important to take the time to slowly read the error messages you get, it will help you in the long run.

    Write the minimal amount of code for the test to run and check the failing test output

    Let’s add some methods to our types

    1. type Rectangle struct {
    2. Width float64
    3. Height float64
    4. }
    5. func (r Rectangle) Area() float64 {
    6. return 0
    7. }
    8. type Circle struct {
    9. Radius float64
    10. }
    11. func (c Circle) Area() float64 {
    12. return 0
    13. }

    The syntax for declaring methods is almost the same as functions and that’s because they’re so similar. The only difference is the syntax of the method receiver func (receiverName RecieverType) MethodName(args).

    When your method is called on a variable of that type, you get your reference to its data via the receiverName variable. In many other programming languages this is done implicitly and you access the receiver via this.

    It is a convention in Go to have the receiver variable be the first letter of the type.

    1. r Rectangle

    If you try to re-run the tests they should now compile and give you some failing output.

    Write enough code to make it pass

    Now let’s make our rectangle tests pass by fixing our new method

    1. func (r Rectangle) Area() float64 {
    2. return r.Width * r.Height
    3. }

    If you re-run the tests the rectangle tests should be passing but circle should still be failing.

    To make circle’s Area function pass we will borrow the Pi constant from the math package (remember to import it).

    1. func (c Circle) Area() float64 {
    2. return math.Pi * c.Radius * c.Radius
    3. }

    Refactor

    There is some duplication in our tests.

    All we want to do is take a collection of shapes, call the Area() method on them and then check the result.

    We want to be able to write some kind of checkArea function that we can pass both Rectangles and Circles to, but fail to compile if we try to pass in something that isn’t a shape.

    With Go, we can codify this intent with interfaces.

    are a very powerful concept in statically typed languages like Go because they allow you to make functions that can be used with different types and create highly-decoupled code whilst still maintaining type-safety.

    Let’s introduce this by refactoring our tests.

    1. func TestArea(t *testing.T) {
    2. checkArea := func(t *testing.T, shape Shape, want float64) {
    3. t.Helper()
    4. got := shape.Area()
    5. if got != want {
    6. t.Errorf("got %.2f want %.2f", got, want)
    7. }
    8. }
    9. t.Run("rectangles", func(t *testing.T) {
    10. rectangle := Rectangle{12, 6}
    11. checkArea(t, rectangle, 72.0)
    12. })
    13. t.Run("circles", func(t *testing.T) {
    14. circle := Circle{10}
    15. checkArea(t, circle, 314.1592653589793)
    16. })
    17. }

    We are creating a helper function like we have in other exercises but this time we are asking for a Shape to be passed in. If we try to call this with something that isn’t a shape, then it will not compile.

    How does something become a shape? We just tell Go what a Shape is using an interface declaration

    1. type Shape interface {
    2. Area() float64
    3. }

    We’re creating a new type just like we did with Rectangle and but this time it is an interface rather than a struct.

    Once you add this to the code, the tests will pass.

    This is quite different to interfaces in most other programming languages. Normally you have to write code to say My type Foo implements interface Bar.

    But in our case

    • Rectangle has a method called Area that returns a float64 so it satisfies the Shape interface
    • Circle has a method called Area that returns a float64 so it satisfies the Shape interface
    • string does not have such a method, so it doesn’t satisfy the interface
    • etc.

    In Go interface resolution is implicit. If the type you pass in matches what the interface is asking for, it will compile.

    Notice how our helper does not need to concern itself with whether the shape is a Rectangle or a Circle or a Triangle. By declaring an interface the helper is decoupled from the concrete types and just has the method it needs to do its job.

    This kind of approach of using interfaces to declare only what you need is very important in software design and will be covered in more detail in later sections.

    Further refactoring

    Now that you have some understanding of structs we can now introduce “table driven tests”.

    are useful when you want to build a list of test cases that can be tested in the same manner.

    The only new syntax here is creating an “anonymous struct”, areaTests. We are declaring a slice of structs by using []struct with two fields, the shape and the want. Then we fill the slice with cases.

    We then iterate over them just like we do any other slice, using the struct fields to run our tests.

    Table based tests can be a great item in your toolbox but be sure that you have a need for the extra noise in the tests. If you wish to test various implementations of an interface, or if the data being passed in to a function has lots of different requirements that need testing then they are a great fit.

    Let’s demonstrate all this by adding another shape and testing it; a triangle.

    Adding a new test for our new shape is very easy. Just add {Triangle{12, 6}, 36.0}, to our list.

    1. func TestArea(t *testing.T) {
    2. areaTests := []struct {
    3. shape Shape
    4. want float64
    5. }{
    6. {Rectangle{12, 6}, 72.0},
    7. {Circle{10}, 314.1592653589793},
    8. {Triangle{12, 6}, 36.0},
    9. }
    10. for _, tt := range areaTests {
    11. got := tt.shape.Area()
    12. if got != tt.want {
    13. t.Errorf("got %.2f want %.2f", got, tt.want)
    14. }
    15. }
    16. }

    Try to run the test

    Remember, keep trying to run the test and let the compiler guide you toward a solution.

    Write the minimal amount of code for the test to run and check the failing test output

    ./shapes_test.go:25:4: undefined: Triangle

    We have not defined Triangle yet

    1. type Triangle struct {
    2. Base float64
    3. Height float64
    4. }

    Try again

    1. ./shapes_test.go:25:8: cannot use Triangle literal (type Triangle) as type Shape in field value:
    2. Triangle does not implement Shape (missing Area method)

    It’s telling us we cannot use a Triangle as a shape because it does not have an Area() method, so add an empty implementation to get the test working

    1. func (t Triangle) Area() float64 {
    2. return 0
    3. }

    Finally the code compiles and we get our error

    shapes_test.go:31: got 0.00 want 36.00

    Write enough code to make it pass

    1. func (t Triangle) Area() float64 {
    2. return (t.Base * t.Height) * 0.5
    3. }

    And our tests pass!

    Refactor

    Again, the implementation is fine but our tests could do with some improvement.

    When you scan this

    1. {Rectangle{12, 6}, 72.0},
    2. {Circle{10}, 314.1592653589793},
    3. {Triangle{12, 6}, 36.0},

    It’s not immediately clear what all the numbers represent and you should be aiming for your tests to be easily understood.

    So far you’ve only been shown syntax for creating instances of structs MyStruct{val1, val2} but you can optionally name the fields.

    Let’s see what it looks like

    1. {shape: Rectangle{Width: 12, Height: 6}, want: 72.0},
    2. {shape: Circle{Radius: 10}, want: 314.1592653589793},
    3. {shape: Triangle{Base: 12, Height: 6}, want: 36.0},

    In Test-Driven Development by Example Kent Beck refactors some tests to a point and asserts:

    The test speaks to us more clearly, as if it were an assertion of truth, not a sequence of operations

    (emphasis mine)

    Now our tests (at least the list of cases) make assertions of truth about shapes and their areas.

    Make sure your test output is helpful

    Remember earlier when we were implementing Triangle and we had the failing test? It printed shapes_test.go:31: got 0.00 want 36.00.

    We knew this was in relation to Triangle because we were just working with it, but what if a bug slipped in to the system in one of 20 cases in the table? How would a developer know which case failed? This is not a great experience for the developer, they will have to manually look through the cases to find out which case actually failed.

    We can change our error message into %#v got %.2f want %.2f. The %#v format string will print out our struct with the values in its field, so the developer can see at a glance the properties that are being tested.

    To increase the readability of our test cases further we can rename the want field into something more descriptive like hasArea.

    One final tip with table driven tests is to use t.Run and to name the test cases.

    By wrapping each case in a t.Run you will have clearer test output on failures as it will print the name of the case

    1. --- FAIL: TestArea (0.00s)
    2. --- FAIL: TestArea/Rectangle (0.00s)
    3. shapes_test.go:33: main.Rectangle{Width:12, Height:6} got 72.00 want 72.10

    And you can run specific tests within your table with go test -run TestArea/Rectangle.

    Here is our final test code which captures this

    1. func TestArea(t *testing.T) {
    2. areaTests := []struct {
    3. name string
    4. shape Shape
    5. hasArea float64
    6. }{
    7. {name: "Rectangle", shape: Rectangle{Width: 12, Height: 6}, hasArea: 72.0},
    8. {name: "Circle", shape: Circle{Radius: 10}, hasArea: 314.1592653589793},
    9. {name: "Triangle", shape: Triangle{Base: 12, Height: 6}, hasArea: 36.0},
    10. }
    11. for _, tt := range areaTests {
    12. // using tt.name from the case to use it as the `t.Run` test name
    13. t.Run(tt.name, func(t *testing.T) {
    14. got := tt.shape.Area()
    15. if got != tt.hasArea {
    16. t.Errorf("%#v got %.2f want %.2f", tt.shape, got, tt.hasArea)
    17. }
    18. })
    19. }
    20. }

    This was more TDD practice, iterating over our solutions to basic mathematic problems and learning new language features motivated by our tests.

    • Declaring structs to create your own data types which lets you bundle related data together and make the intent of your code clearer
    • Declaring interfaces so you can define functions that can be used by different types (parametric polymorphism)
    • Table based tests to make your assertions clearer and your suites easier to extend & maintain

    This was an important chapter because we are now starting to define our own types. In statically typed languages like Go, being able to design your own types is essential for building software that is easy to understand, to piece together and to test.

    As you become more familiar with Go you start to see the real strength of interfaces and the standard library. You’ll learn about interfaces defined in the standard library that are used everywhere and by implementing them against your own types you can very quickly re-use a lot of great functionality.