oinume journal

Scratchpad of what I learned

Satisfying a large interface quickly in Go

Sometimes it's painful to safisfy a large interface in Go. Here is a simple answer for this, just embed interface on struct like bellow:

package main

import (
    "fmt"
)

type Foo interface {
    MethodA()
    MethodB()  
    MethodC()
    MethodD()   
}

type FooImpl struct {
    Foo
}

func (fi *FooImpl) MethodA() {
    fmt.Println("MethodA called")
}

func main() {
    foo := new(FooImpl)
    foo.MethodA() // Implemented
    foo.MethodB() // Not implemented, runtime error will happen
}

You can check the result on https://play.golang.org/p/0y8ICTWCfpy.

  • MethodA called is printed
  • And then a runtime error happens by calling foo.MethodB

This technique is useful in unit test.