Created
November 21, 2018 16:54
-
-
Save bojand/1b7f83ba1b2922fed577395d5b3e625f to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
type Config struct { | |
Secure bool | |
Timeout time.Duration | |
Host string | |
Port int | |
} | |
func NewConfig(options ...func(*Config)) *Config { | |
c := &Config{} | |
for _, option := range options { | |
option(c) | |
} | |
return c | |
} | |
func main() { | |
host := func(c *Config) { | |
c.Host = "addr" | |
} | |
port := func(c *Config) { | |
c.Port = 5 | |
} | |
timeout := func(c *Config) { | |
c.Timeout = 15 * time.Second | |
} | |
cfg := NewConfig(host, port, timeout) | |
fmt.Printf("%+v", cfg) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment