Skip to content

Instantly share code, notes, and snippets.

@podanypepa
Created Mar 19, 2021
Embed
What would you like to do?
// 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