Last active
October 25, 2019 23:25
-
-
Save efueyo/01bc440d1df801bd56ad6fb38ad1590d to your computer and use it in GitHub Desktop.
Golang Configuration
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
// 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