Skip to content

Instantly share code, notes, and snippets.

@efueyo
Last active October 25, 2019 23:25
Show Gist options
  • Save efueyo/01bc440d1df801bd56ad6fb38ad1590d to your computer and use it in GitHub Desktop.
Save efueyo/01bc440d1df801bd56ad6fb38ad1590d to your computer and use it in GitHub Desktop.
Golang Configuration
// Bad
const bark = "woof"
type Dog struct{}
// Bark prints the dog's bark
func (d *Dog) Bark() {
fmt.Println(bark)
}
// Better
const defaultBark = "woof"
type Dog struct {
bark string
}
// Bark prints the dog's bark
func (d *Dog) Bark() {
fmt.Println(d.bark)
}
// ConfigFunc are functions that can be used to configure a dog
type ConfigFunc func(*Dog)
// Bark sets the dog's barking sound
func Bark(bark string) ConfigFunc {
return func(d *Dog) {
d.bark = bark
}
}
// ProvideDog provides a new Dog instance
func ProvideDog(configs ...ConfigFunc) *Dog {
d := &Dog{defaultBark}
for _, config := range configs {
config(d)
}
return d
}
// Usage:
mydog := ProvideDog(Bark("guau"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment