Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ackage main
import "fmt"
// assume this is the original implementation of the callback:
/*
// by default the callback say hello only to jane
PrintCallback(name string) bool {
if name == "jane" {
return true
}
return false
}
*/
// and this function then use the callback
func PrintHello(name string) {
if PrintCallback(name) {
fmt.Println("hello world: " + name)
} else {
fmt.Println("not going to say hello to: " + name)
}
}
// now, use a closure instead of a regular function to allow override
var PrintCallback = func(name string) bool {
if name == "jane" {
return true
}
return false
}
// this is added for testing purposes
// this callback never says hello
func MockPrintCallback(name string) bool {
return false
}
func main() {
fmt.Println("say hello to jane")
PrintHello("jane")
fmt.Println("don't say hello to john")
PrintHello("john")
// now inject the test method
PrintCallback = MockPrintCallback
fmt.Println("won't say hello to jane either")
PrintHello("jane")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment