Not sure what the correct name is, but I'm looking for more information about "chained function calls" in Go. For example:
foo.DoSomething().WithThisOptionalThing()
So I can use foo.DoSomething()
but with the possibility to add .WithThisOptionalThing()
which does something extra's. Is this possible? Please point me in the right direction / provide some examples.
Basically, you make all your configuration functions keep returning the main "object" while you chain things together and have a final "Go" function or whatever you want to call it to make it perform the action.
Here's an example on play
package main
import (
"fmt"
)
func main() {
DoSomething().Go()
DoSomething().WithThisOptionalThing().Go()
}
type Chainable struct {
thing bool
}
func DoSomething() *Chainable {
return &Chainable{}
}
func (c *Chainable) WithThisOptionalThing() *Chainable {
c.thing = true
return c
}
func (c *Chainable) Go() error {
// Actually do something now that it's been configured
fmt.Println("Thing is", c.thing)
return nil
}
You just need to know: When it comes to chaining things your methods should either always
pointers
and return pointers
or
values
and return values
or
values
and return pointers
at least they're the working combinations known to me. I couldn't find any documentation on this. If you know what's going on please let me know.