Skip to content

Instantly share code, notes, and snippets.

@tokubass
Created October 8, 2018 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tokubass/9821ac6d2ac1b3af8300b1f4afeeb063 to your computer and use it in GitHub Desktop.
Save tokubass/9821ac6d2ac1b3af8300b1f4afeeb063 to your computer and use it in GitHub Desktop.
任意個のオプションを渡す
package main
import "fmt"
func main() {
Connect(Url("http://hoge.com"))
}
func Connect(options ...Option) error {
opts := GetDefaultOptions()
//{Url: AllowReconnect:true}
fmt.Printf("%+v\n", opts)
for _, opt := range options {
if opt != nil {
if err := opt(&opts); err != nil {
return err
}
}
}
//{Url:http://hoge.com AllowReconnect:true}
fmt.Printf("%+v\n", opts)
return nil
}
type Options struct {
Url string
AllowReconnect bool
}
func GetDefaultOptions() Options {
return Options{
AllowReconnect: true,
}
}
type Option func(*Options) error
func Url(url string) Option {
return func(o *Options) error {
o.Url = url
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment