Last active
August 29, 2015 14:05
-
-
Save bachue/c6ca089948ea78d97328 to your computer and use it in GitHub Desktop.
Golang Interface Match
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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