Created
December 15, 2023 11:27
-
-
Save Guaderxx/1005c06f30e1929fd887d2c08397d5a9 to your computer and use it in GitHub Desktop.
functional options pattern
This file contains hidden or 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 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