Skip to content

Instantly share code, notes, and snippets.

@abdivasiyev
Created May 1, 2024 17:39
Show Gist options
  • Save abdivasiyev/ef48a25c01c8c16cfbf950f7131d076b to your computer and use it in GitHub Desktop.
Save abdivasiyev/ef48a25c01c8c16cfbf950f7131d076b to your computer and use it in GitHub Desktop.
Optional arguments implementation
// Usage:
//
// SomeFn(1, "test", WithArg1("optional 1"), WithArg2(true))
//
package some_pkg
type Option func(*option)
type option struct {
arg1 string
arg2 bool
}
func SomeFn(requiredArg1 int, requiredArg2 string, options ...Option) {
var optionalArgs option
for _, opt := range options {
opt(&optionalArgs)
}
// some stuff
}
func WithArg1(arg1 string) Option {
return func(opt *option) {
opt.arg1 = arg1
}
}
func WithArg2(arg2 bool) Option {
return func(opt *option) {
opt.arg2 = arg2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment