Skip to content

Instantly share code, notes, and snippets.

@Guaderxx
Created December 15, 2023 11:27
Show Gist options
  • Save Guaderxx/1005c06f30e1929fd887d2c08397d5a9 to your computer and use it in GitHub Desktop.
Save Guaderxx/1005c06f30e1929fd887d2c08397d5a9 to your computer and use it in GitHub Desktop.
functional options pattern
package main
import "fmt"
type Student struct {
Name string
Age int
Address *string // optional
PhoneNumber *int // optional
}
type OptionalStudentValues func(*Student)
func NewStudent(name string, age, int, opts ...OptionalStudentValues) *Student {
stu := &Student{
Name: name,
Age: age,
}
if len(opts) > 0 {
for _, opt := range opts {
opt(stu)
}
}
return stu
}
func WithAddress(addr string) OptionalStudentValues {
return func(s *Student) {
s.Address = &addr
}
}
func WithPhoneNumber(num int) OptionalStudentValues {
return func(s *Student) {
s.PhoneNumber = &int
}
}
func main() {
stuAddr := "Addr"
stuPhone := 13966272617
stu := NewStudent("Ader", 99, WithAddress(stuAddr), WithPhoneNumber(stuPhone))
fmt.Println(stu)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment