Skip to content

Instantly share code, notes, and snippets.

@jtacoma
Created September 26, 2012 03:41
Show Gist options
  • Save jtacoma/3785876 to your computer and use it in GitHub Desktop.
Save jtacoma/3785876 to your computer and use it in GitHub Desktop.
Adding Methods to an Interface in Go
// This package demonstrates a technique for (very nearly) adding methods
// to an interface. The code works and runs as is.
package main
import "fmt"
// A simple custom type
type Cell int
// CellSetMinimal is a (very) minimal interface to be easily implemented
// by custom collections.
type CellSetMinimal interface {
Do(func(Cell))
}
// CellSet is somewhat more fleshed out interface to be implemented by
// more ambitious custom collections.
type CellSet interface {
CellSetMinimal
Len() int
Has(Cell) bool
}
// CellSetWrapper wraps any implementation of CellSetMinimal to provide
// a default, though pessimal, implementation of CellSet.
type CellSetWrapper struct {
CellSetMinimal
}
func (w CellSetWrapper) Len() (ln int) {
w.Do(func(_ Cell) {
ln += 1
})
return
}
func (w CellSetWrapper) Has(cell Cell) (yes bool) {
w.Do(func(c Cell) {
yes = yes || (cell == c)
})
return
}
// CellSlice is a sample implementation of CellSetMinimal
type CellSlice []Cell
func (cs CellSlice) Do(do func(Cell)) {
for _, c := range cs {
do(c)
}
}
func main() {
var cs CellSlice
cs = append(cs, Cell(42))
// Note: braces not parentheses on the next line!
w := CellSetWrapper{cs}
fmt.Println("cs.Len() =", w.Len())
fmt.Println("cs.Has(42) =", w.Has(Cell(42)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment