github.com/szq-123/codingpractice@v0.0.0-20240430111904-2778dfaf7994/golang/coding/function_option.go (about)

     1  package coding
     2  
     3  // reference: https://coolshell.cn/articles/21146.html
     4  
     5  type Server struct {
     6  	Name string
     7  }
     8  
     9  // 方式1 Function Option
    10  
    11  type Option func(*Server)
    12  
    13  func Name(name string) Option {
    14  	return func(server *Server) {
    15  		server.Name = name
    16  	}
    17  }
    18  
    19  func NewServer1(options ...Option) *Server {
    20  	server := &Server{}
    21  	for _, opt := range options {
    22  		opt(server)
    23  	}
    24  	return server
    25  }
    26  
    27  // 方式2
    28  
    29  type Config struct {
    30  	Name string
    31  }
    32  
    33  func NewServer2(config *Config) *Server {
    34  	return &Server{Name: config.Name}
    35  }
    36  
    37  // 方式3
    38  
    39  func (s *Server) WithName(name string) *Server {
    40  	s.Name = name
    41  	return s
    42  }