Last active
June 15, 2018 15:51
-
-
Save mmcloughlin/464e76358cad80a15c9311d86e61ea38 to your computer and use it in GitHub Desktop.
Golang method expressions satisfy function types
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" | |
| // 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