Skip to content

Instantly share code, notes, and snippets.

@podanypepa
Created March 19, 2021 08:51
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 podanypepa/c9c7531a818ce197830f690070e6dd3f to your computer and use it in GitHub Desktop.
Save podanypepa/c9c7531a818ce197830f690070e6dd3f to your computer and use it in GitHub Desktop.
// Functional Options Pattern
package main
import (
"fmt"
)
func main() {
ct := NewCompany(
WitICO("11"),
WithName("pepa"),
)
fmt.Println(ct)
}
type Company struct {
ID string
Name string
ICO string
}
func NewCompany(opt ...Options) *Company {
nc := &Company{}
for _, o := range opt {
o(nc)
}
return nc
}
type Options func(*Company)
func WithID(id string) Options {
return func(c *Company) {
c.ID = id
}
}
func WithName(name string) Options {
return func(c *Company) {
c.Name = name
}
}
func WitICO(ico string) Options {
return func(c *Company) {
c.ICO = ico
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment