golang 编程笔记

【golang】可选项使用闭包传入参数,增加代码质量

2020-03-26  本文已影响0人  dongzd

可选项与闭包结合

var (
    DefaultArea = "苏州"
    DefaultHigh = uint32(170)
)

type Options struct {
    Area string
    High uint32
}
type Option interface {
    Apply(*Options)
}
type OptionFunc func(*Options)

func (f OptionFunc) Apply(o *Options) {
    f(o)
}

func WithArea(area string) Option {
    return OptionFunc(func(o *Options) {
        o.Area = area
    })
}

func WithHigh(high uint32) Option {
    return OptionFunc(func(o *Options) {
        o.High = high
    })
}

type User struct {
    Name string
    Age  uint32
    Opts *Options
}

func (u User) String() string {
    return fmt.Sprintf("%s,%v岁,身高:%v,住在:%s", u.Name, u.Age, u.Opts.High, u.Opts.Area)
}
func main() {
    user1 := NewUser("小红", 16)
    user2 := NewUser("小明", 17, WithArea("南京"), WithHigh(10))

    fmt.Println(user1)
    fmt.Println(user2)
}

func NewUser(name string, age uint32, opts ...Option) *User {
    user := &User{}
    user.Name = name
    user.Age = age

    op := &Options{
        Area: DefaultArea,
        High: DefaultHigh,
    }

    for _, p := range opts {
        p.Apply(op)
    }

    user.Opts = op

    return user

}

上一篇下一篇

猜你喜欢

热点阅读