美文网首页
golang构造函数

golang构造函数

作者: charley_z | 来源:发表于2019-12-20 18:26 被阅读0次
    package main
    
    import "fmt"
    
    /**
     * 构造函数
     * 上班类
     */
    type Work struct {
        opts options
    }
    type options struct {
        startTime string
        lunchTime string
        endTime   string
    }
    
    var (
        lunTimeDefault = "中午十二点"
    )
    
    type Option func(o *options)
    
    func StartTime(s string) Option {
        return func(opts *options) {
            opts.startTime = s
        }
    }
    
    func EndTime(s string) Option {
        return func(opts *options) {
            opts.endTime = s
        }
    }
    
    func NewWork(opts ...Option) *Work {
        workOptions := options{}
        for _, opt := range opts {
            opt(&workOptions)
        }
        work := new(Work)
        work.opts = workOptions
        if work.opts.lunchTime == "" {
            work.opts.lunchTime = lunTimeDefault
        }
        return work
    }
    
    func main() {
        commonOpts := []Option{
            StartTime("九点半"),
            EndTime("二十点"),
        }
    
        work := NewWork(commonOpts...)
        fmt.Printf("%+v", work.opts)
    }
    
    
    

    参考

    https://blog.keyboardman.me/2018/01/03/grpc-functional-options-patter/

    https://www.jianshu.com/p/0345dea9b63d?utm_campaign=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com

    相关文章

      网友评论

          本文标题:golang构造函数

          本文链接:https://www.haomeiwen.com/subject/isoogftx.html