Skip to content

Instantly share code, notes, and snippets.

@bojand
Created November 21, 2018 16:54
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 bojand/1b7f83ba1b2922fed577395d5b3e625f to your computer and use it in GitHub Desktop.
Save bojand/1b7f83ba1b2922fed577395d5b3e625f to your computer and use it in GitHub Desktop.
Functional options
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