Skip to content

Instantly share code, notes, and snippets.

@bachue
Last active August 29, 2015 14:05
Show Gist options
  • Save bachue/c6ca089948ea78d97328 to your computer and use it in GitHub Desktop.
Save bachue/c6ca089948ea78d97328 to your computer and use it in GitHub Desktop.
Golang Interface Match
package main
import (
"fmt"
)
type Handler func(int)
func test(handler Handler) {
handler(1)
}
func main() {
test(func(i int) {
fmt.Printf("%d\n", i)
})
}
/**
Compile Failure:
cannot use new(HandlerImpl) (type *HandlerImpl) as type CanHandle in argument to test:
*HandlerImpl does not implement CanHandle (wrong type for Handle method)
have Handle(func(int))
want Handle(Handler)
Fix method:
Replace Handler with func(int), or replace func(int) with Handler
**/
package main
import (
"fmt"
)
type Handler func(int)
type CanHandle interface {
Handle(Handler)
}
type HandlerImpl struct {
}
func (handler *HandlerImpl) Handle(do func(int)) {
do(1)
}
func test(handler CanHandle) {
handler.Handle(func(i int) {
fmt.Printf("%d\n", i)
})
}
func main() {
test(new(HandlerImpl))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment