I am porting a client to an API from python. The original implementation uses optional parameters as
def createIntAttribute(attr_name, default_value=None, is_array=False)
which create an integer attribute on database with or without a default value as in:
createIntAttribute("numUsers") # No default attribute
createIntAttribute("numUsers", 0) # Default attribute of 0
How can this be implemented in Go?
Some approaches I have considered are:
defaultValue *int
&
on every use and doesn't support literalsmypackage.NewOptionalStringArray([]string{"hello", "world"})
func createIntAttribute(name string, optionals ...interface{})
What would be the best way to implement this?
One approach is to use the Functional Options Pattern. See the demo below:
package main
import (
"log"
)
type options struct {
hasDefault bool
defaultValue int
}
type option func(*options)
func withDefault(value int) option {
return func(o *options) {
o.hasDefault = true
o.defaultValue = value
}
}
func createIntAttribute(name string, setters ...option) {
o := &options{}
for _, setter := range setters {
setter(o)
}
log.Println(name, o)
}
func main() {
createIntAttribute("test1")
createIntAttribute("test1", withDefault(10))
}
This approach can be more user friendly (maybe) when implemented as method chain:
package main
import (
"log"
)
type createIntAttributeParams struct {
name string
hasDefault bool
defaultValue int
}
// mandatory parameters here
func createIntAttribute(name string) *createIntAttributeParams {
return &createIntAttributeParams{
name: name,
}
}
// optional parameter
func (p *createIntAttributeParams) withDefault(value int) *createIntAttributeParams {
p.hasDefault = true
p.defaultValue = value
return p
}
// other with* functions to set more optional parameters
// execute
func (p *createIntAttributeParams) do() {
log.Println(*p)
}
func main() {
createIntAttribute("test1").do()
createIntAttribute("test1").withDefault(10).do()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With