美文网首页
go 的选项模式

go 的选项模式

作者: wayyyy | 来源:发表于2022-02-13 00:12 被阅读0次

    现在有个结构体如下定义:

    type Server struct {
        host string
        port int
    }
    

    我们需要初始化结构体,如果是其他语言,函数支持默认参数:

    func NewServer(host="0:0:0:0", port="8080") *Server {
        return &Server{host, port}
    }
    

    但是,go语言函数不支持默认参数,同时即使go语言支持默认参数,但是如果配置项过多,那么每一个配置项都得写一个默认参数,也不现实。
    那么,在go语言中,我们怎么优雅的给其初始化呢,这时,就需要利用选项模式了(option)。

    首先,我们定义一个option函数类型:

    type option func(*Server)
    

    它接收一个参数:*Server
    然后定义一个NewServer函数,它接收一个 Option类型的不定参数:

    func NewServer(options ...option) *Server {
        svr := &Server{}
        for _, f := range options {
            f(svr)
        }    
        return svr
    }
    

    最后,再直接定义一系列返回 Option的函数

    func WithHost(host string) Option {
        return func(s *Server) {
            s.host  = host
        }
    }
    
    func WithPort(port int) Option {
        return func(s * Server) {
            s.port = port
        }
    }
    

    使用时,直接:

    func main() {
        svr := NewServer(
            WithHost("localhost"),
            WithPort(8080),
        )
    }
    

    参考资料
    1、https://juejin.cn/post/6844903729313873927
    2、https://mp.weixin.qq.com/s/_7ofuy2Wp__3B9esO_2oag

    相关文章

      网友评论

          本文标题:go 的选项模式

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