Last active
April 1, 2020 07:27
-
-
Save pomkine/ee89130adacfd7b1468b69a41aff0f47 to your computer and use it in GitHub Desktop.
Go functional options
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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