Last active
June 4, 2021 07:30
-
-
Save QuantumGhost/f4adf1518f5165661d4ce9cfe99037b6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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