Ensure a type implements an interface at compile time in Go-Collection of common programming errors

I don’t like the idea of making compiler throw errors by putting dummy lines in the main code. That’s a smart solution that works, but I prefer to write a test for this purpose.

Assuming that we have:

type Intfc interface { Func() }
type Typ int
func (t Typ) Func() {}

This test makes sure Typ implements Intfc:

package main

import (
    "reflect"
    "testing"
)

func TestTypes(t *testing.T) {
    var interfaces struct {
        intfc Intfc
    }
    var typ Typ
    v := reflect.ValueOf(interfaces)
    testType(t, reflect.TypeOf(typ), v.Field(0).Type())
}

// testType checks if type t1 implements interface t2
func testType(t *testing.T, t1, t2 reflect.Type) {
    if !t1.Implements(t2) {
        t.Errorf("%v does not implement %v", t1, t2)
    }
}

You can check all of your types and interfaces by adding them to TestTypes function. Writing tests for Go is introduced here.