The Go (Golang) Functiona Options Pattern is a way, a pattern of structuring your structs in Go by designing a very expressive and flexible set of APIs that will help with the configuration and initialisation of your struct.
Go 函数式选项模式 是一种在 Go 中构建结构的模式,它通过设计一组非常富有表现力和灵活的 API 来帮助配置和初始化结构
来自:Golang Functional Options Pattern | Golang Cafe
packageserverimport("errors""log""time")const(defaultHost="127.0.0.1"defaultPort=8000defaultTimeout=time.MinutedefaultMaxConn=120)typeServerstruct{HoststringPortintTimeouttime.DurationMaxConnint}// All server attribute can edittypeServerOptionsstruct{HoststringPortintTimeouttime.DurationMaxConnint}typeServerOptioninterface{apply(*ServerOptions)}typefuncServerOptionstruct{ffunc(*ServerOptions)}func(fofuncServerOption)apply(option*ServerOptions){fo.f(option)}funcnewFuncServerOption(ffunc(*ServerOptions))*funcServerOption{return&funcServerOption{f:f,}}// All Withxx function to edit optionfuncWithHost(hoststring)ServerOption{returnnewFuncServerOption(func(option*ServerOptions){option.Host=host})}funcWithPort(portint)ServerOption{returnnewFuncServerOption(func(option*ServerOptions){option.Port=port})}funcWithTimeout(timeouttime.Duration)ServerOption{returnnewFuncServerOption(func(option*ServerOptions){option.Timeout=timeout})}funcWithMaxConn(maxConnint)ServerOption{returnnewFuncServerOption(func(option*ServerOptions){option.MaxConn=maxConn})}// Create New Object with option parametersfuncNewServer(opts...ServerOption)*Server{options:=ServerOptions{Host:defaultHost,Port:defaultPort,Timeout:defaultTimeout,MaxConn:defaultMaxConn,}for_,opt:=rangeopts{opt.apply(&options)}return&Server{Host:defaultHost,Port:defaultPort,Timeout:defaultTimeout,MaxConn:defaultMaxConn,}}func(s*Server)Start()error{log.Printf("Server: %v",s)returnerrors.New("Error")}