We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
package main type Server struct { maxConn int id string tls bool } // Problem: Parameter will grow when we need more configs func newServer(maxConn int, id string, tls bool) *Server { return &Server{ maxConn: maxConn, id: id, tls: tls, } func main() { s := NewServer(20, "id", false) fmt.Printf("%+v\n", s) }
package main type OptFunc func(*Opts) type Opts struct { maxConn int id string tls bool } func defaultOpts() Opts { return Opts{ maxConn: 10, id: "default", tls: false, } } func withTLS(opts *Opts) { opts.tls = true } func withMaxConn(n int) OptFun { return func(opts *Opts) { opts.maxConn = n } } type Server struct { Opts } func NewServer(opts ...OptFunc) *Server { o := defailtOpts() for _, fn := range opts { fn(&o) } return &Server{ Opts: o, } } func main() { s := NewServer(withTLS, withMaxConn(20)) fmt.Printf("%+v\n", s) }
The text was updated successfully, but these errors were encountered:
japananh
No branches or pull requests
Best practice struct configuration pattern for Golang
Before
After
The text was updated successfully, but these errors were encountered: