Skip to content

Instantly share code, notes, and snippets.

@yuvalif
Last active May 9, 2018 19:25
Show Gist options
  • Save yuvalif/006c48c563f264041f4ada5f90ddfd0c to your computer and use it in GitHub Desktop.
Save yuvalif/006c48c563f264041f4ada5f90ddfd0c to your computer and use it in GitHub Desktop.
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