A Tip for Defining Interfaces for Structs Whose Methods Take Enum Values in Go
This article was automatically translated from Japanese by AI. Read the original Japanese version →
In Go, there seems to be a convention where libraries don't provide interfaces themselves, and instead callers define their own if and when they need them. Since Go interfaces are duck-typed, that usually works out just fine.
However, when a method takes an enum value as an argument, simply copying and pasting the method signature causes the interface itself to depend on the concrete implementation, so you need a small workaround.
All you're really doing is defining a matching enum alongside the interface, so it's nothing complicated, though folks who aren't used to DI and the like might get tripped up by it.
Here's an example implementation. Hope it helps!
package main import "fmt" // 例えば、以下のようなinterface化したいライブラリ(?)があったとする。 type Hoge struct { a int } type Mode int const ( ModeOne = iota ModeTwo ) func NewHoge(a int) *Hoge { return &Hoge{a: a} } func (h Hoge) Mul(m Mode) int { return h.a * int(m) } // ここから下はインターフェース type MulerMode int const ( MulerModeOne = iota MulerModeTwo ) // 普通にやるとMulの引数の型にModeを指定してしまうが、そうするとInterfaceが実装に依存してしまう // ここでは同じ値域のenum、MulerModeをinterfaceとセットで用意して回避する type Muler interface { Mul(m MulerMode) int } // ここから下はインターフェースを通じてHogeを使いたい場合 type MulerImpl struct { Hoge } func NewMulerImpl(a int) *MulerImpl { return &MulerImpl{Hoge: Hoge{a: a}} } func (m *MulerImpl) Mul(mm MulerMode) int { var md Mode // ここでenum同士のマッピングをする switch mm { case MulerModeOne: md = ModeOne case MulerModeTwo: md = ModeTwo default: return 0 // 本当はエラーとかだと思う } return m.Hoge.Mul(md) } // 実際に呼び出す func main() { var m Muler m = NewMulerImpl(1) fmt.Print(m.Mul(MulerModeOne)) }