Default Values to Function Parameters
Functional options pattern
- Create a struct to hold our arguments:
type GreetingOptions struct {
Name string
Age int
}
- Now let’s define the function:
func Greet(options GreetingOptions) string {
return "My name is " + options.Name + " and I am " + strconv.Itoa(options.Age) + " years old."
}
- Define functional options for the fields in the struct:
type GreetingOption func(*GreetingOptions)
func WithName(name string) GreetingOption {
return func(o *GreetingOptions) {
o.Name = name
}
}
func WithAge(age int) GreetingOption {
return func(o *GreetingOptions) {
o.Age = age
}
}
- Create a wrapper:
func GreetWithDefaultOptions(options ...GreetingOption) string {
opts := GreetingOptions{
Name: "Aiden",
Age: 30,
}
for _, o := range options {
o(&opts)
}
return Greet(opts)
}
- Use:
greeting := GreetWithDefaultOptions(WithName("Alice"), WithAge(20))
// Out: "My name is Alice and I am 20 years old."