Created
January 30, 2019 12:22
-
-
Save wuriyanto48/e6c7f249a2966c40c8d479c6c951bcad to your computer and use it in GitHub Desktop.
golang function options
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" | |
| ) | |
| func main() { | |
| c := Call("wuriyanto", aOptions("self"), bOptions("taught coder"), cOptions(true)) | |
| fmt.Println(c) | |
| } | |
| type Option struct { | |
| f func(*options) | |
| } | |
| type options struct { | |
| x string | |
| a string | |
| b string | |
| c bool | |
| } | |
| func aOptions(a string) Option { | |
| return Option{func(o *options) { | |
| o.a = a | |
| }} | |
| } | |
| func bOptions(b string) Option { | |
| return Option{func(o *options) { | |
| o.b = b | |
| }} | |
| } | |
| func cOptions(c bool) Option { | |
| return Option{func(o *options) { | |
| o.c = c | |
| }} | |
| } | |
| func Call(z string, opts ...Option) string { | |
| o := &options{ | |
| x: "wuriyanto", | |
| } | |
| for _, option := range opts { | |
| option.f(o) | |
| } | |
| return fmt.Sprintf("x = %s\na = %s\nb = %s\nc = %t", o.x, o.a, o.b, o.c) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment