Created
May 1, 2024 17:39
-
-
Save abdivasiyev/ef48a25c01c8c16cfbf950f7131d076b to your computer and use it in GitHub Desktop.
Optional arguments implementation
This file contains 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
// 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