Skip to content

Instantly share code, notes, and snippets.

@mmcloughlin
Last active June 15, 2018 15:51
Show Gist options
  • Select an option

  • Save mmcloughlin/464e76358cad80a15c9311d86e61ea38 to your computer and use it in GitHub Desktop.

Select an option

Save mmcloughlin/464e76358cad80a15c9311d86e61ea38 to your computer and use it in GitHub Desktop.
Golang method expressions satisfy function types
package main
import "fmt"
// GreetingFunc builds a greeting from a name.
type GreetingFunc func(string) string
// Formatted builds a greeting based on a printf-style format string.
type Formatted struct {
Format string
}
// Greeting returns a greeting to who based on the format string.
func (f *Formatted) Greeting(who string) string {
return fmt.Sprintf(f.Format, who)
}
func main() {
f := &Formatted{
Format: "Hello, %s!",
}
// Note the method f.Greeting has type GreetingFunc
var g GreetingFunc = f.Greeting
fmt.Println(g("World"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment