Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Created January 30, 2019 12:22
Show Gist options
  • Select an option

  • Save wuriyanto48/e6c7f249a2966c40c8d479c6c951bcad to your computer and use it in GitHub Desktop.

Select an option

Save wuriyanto48/e6c7f249a2966c40c8d479c6c951bcad to your computer and use it in GitHub Desktop.
golang function options
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