1. package main
    2. import "fmt"
    3. type options struct {
    4. cache bool
    5. logger string
    6. }
    7. type Option interface {
    8. apply(*options)
    9. }
    10. type cacheOption bool
    11. func (c cacheOption) apply(opts *options) {
    12. opts.cache = bool(c)
    13. }
    14. func WithCache(c bool) Option {
    15. return cacheOption(c)
    16. }
    17. type loggerOption struct {
    18. Log string
    19. }
    20. func (l loggerOption) apply(opts *options) {
    21. opts.logger = l.Log
    22. }
    23. func WithLogger(log string) Option {
    24. return loggerOption{Log: log}
    25. }
    26. // Open creates a connection.
    27. func Open(
    28. addr string,
    29. opts ...Option,
    30. ){
    31. options := options{
    32. cache: true,
    33. logger: "hello",
    34. }
    35. fmt.Println(">>addr: ",addr)
    36. fmt.Println(">>opts: ",opts)
    37. for _, o := range opts {
    38. o.apply(&options)
    39. }
    40. }
    41. func main(){
    42. var option Option
    43. option = new(cacheOption)
    44. option.apply(&options{cache:true})
    45. var option1 Option
    46. option1 = new(loggerOption)
    47. option1.apply(&options{logger:"hi,"})
    48. Open("localhost",[]Option{option,option1}...)
    49. }