Skip to content

Instantly share code, notes, and snippets.

@QuantumGhost
Last active June 4, 2021 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save QuantumGhost/f4adf1518f5165661d4ce9cfe99037b6 to your computer and use it in GitHub Desktop.
Save QuantumGhost/f4adf1518f5165661d4ce9cfe99037b6 to your computer and use it in GitHub Desktop.
package main
import "time"
// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
type Client struct {
addr string
timeout time.Duration
}
type Option func(client *Client)
func NewClient(opts ...Option) Client {
client := Client{}
for _, opt := range opts {
opt(&client)
}
return client
}
func Addr(addr string) Option {
return Option(func(client *Client) {
client.addr = addr
})
}
func Timeout(timeout time.Duration) Option {
return Option(func(client *Client) {
client.timeout = timeout
})
}
// How to use
func main() {
client := NewClient(Addr("127.0.0.1"), Timeout(2 * time.Second))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment