1. type Options struct {
    2. FieldA string
    3. FieldB string
    4. FieldC string
    5. }
    6. func defaultOptions() *Options {
    7. return &Options{}
    8. }
    1. type Option func(*Options)
    2. func WithA(a string) Option {
    3. return func(o *Options) {
    4. o.FieldA = a
    5. }
    6. }
    7. func WithB(b string) Option {
    8. return func(o *Options) {
    9. o.FieldB = b
    10. }
    11. }
    12. func WithC(c string) Option {
    13. return func(o *Options) {
    14. o.FieldC = c
    15. }
    16. }
    1. package main
    2. import "fmt"
    3. func main() {
    4. doSomething()
    5. doSomething(WithA("this is the filed a"))
    6. doSomething(WithA("this is the filed a"), WithB("this is the filed b"))
    7. doSomething(WithA("this is the filed a"), WithB("this is the filed b"), WithC("this is the filed c"))
    8. }
    9. func doSomething(opts ...Option) {
    10. o := defaultOptions()
    11. for _, opt := range opts {
    12. opt(o)
    13. }
    14. fmt.Printf("%+v\n", o)
    15. }

    image.pngo