Created
October 8, 2018 09:57
-
-
Save tokubass/9821ac6d2ac1b3af8300b1f4afeeb063 to your computer and use it in GitHub Desktop.
任意個のオプションを渡す
This file contains 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() { | |
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