Go编程构造函数可选参数-FUNCTIONAL OPTIONS
go的构造函数的参数一般可以直接写死,传config结构体,还有一种为functional options,这种方式主要是方便扩展 有良好的兼容性,这里mark下。
参考:https://coolshell.cn/articles/21146.html
package main
import "time"
type Server struct {
Host string
Port int
Timeout time.Duration
MaxHandle int
}
func (Server) Start() error {
// do something
return nil
}
type Option func(*Server)
func NewServer(host string, port int, options ...Option) *Server {
srv := Server{
host,
port,
30 * time.Second,
100,
}
for _, option := range options {
option(&srv)
}
return &srv
}
func Timeout(n time.Duration) Option {
return func(s *Server) {
s.Timeout = n
}
}
func MaxHandle(n int) Option {
return func(s *Server) {
s.MaxHandle = n
}
}
func main() {
srv := NewServer("192.168.1.1", 80, Timeout(10*time.Second), MaxHandle(100))
srv.Start()
}
