Skip to content

Instantly share code, notes, and snippets.

@pomkine
Last active April 1, 2020 07:27
Show Gist options
  • Save pomkine/ee89130adacfd7b1468b69a41aff0f47 to your computer and use it in GitHub Desktop.
Save pomkine/ee89130adacfd7b1468b69a41aff0f47 to your computer and use it in GitHub Desktop.
Go functional options
type Server struct {
addr string
timeout int
retry int
speed int
}
func NewServer(addr string, opts ...func(*Server)) (*Server, error) {
srv := new(Server)
srv.addr = addr
for _, opt := range opts {
opt(srv)
}
return srv, nil
}
func main() {
//default
_, _ = NewServer("localhost")
_, _ = NewServer("localhost", WithTimeout(3000), WithRetry(3))
}
func WithTimeout(timeout int) func(*Server) {
return func(server *Server) {
server.timeout = timeout
}
}
func WithRetry(retry int) func(*Server) {
return func(server *Server) {
server.retry = retry
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment