Created
February 24, 2020 18:44
-
-
Save TeddyDD/72df7a2254519511675004708ff39761 to your computer and use it in GitHub Desktop.
Go option funcs pattern
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" | |
type Person struct { | |
Name string | |
Age int | |
} | |
type personOption func(*Person) | |
func name(n string) personOption { | |
return func(p *Person) { | |
p.Name = n | |
} | |
} | |
func age(a int) personOption { | |
return func(p *Person) { | |
p.Age = a | |
} | |
} | |
func NewPerson(opts ...personOption) *Person { | |
p := &Person{} | |
for _, o := range opts { | |
o(p) | |
} | |
return p | |
} | |
func main() { | |
d := NewPerson(name("Daniel"), age(27)) | |
fmt.Printf("%+v\n", d) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment