Skip to content

Instantly share code, notes, and snippets.

@derekchiang
Last active February 16, 2020 13:25
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save derekchiang/c9709eace4b588353ec9df32d845ac9c to your computer and use it in GitHub Desktop.
Save derekchiang/c9709eace4b588353ec9df32d845ac9c to your computer and use it in GitHub Desktop.
package main
import "fmt"
// WithPrefix
type prefixOption struct{}
func WithPrefix() interface {
GetOption
DeleteOption
} {
return &prefixOption{}
}
func (o *prefixOption) SetGetOption(opts *getOptions) {
opts.Prefix = true
}
func (o *prefixOption) SetDeleteOption(opts *deleteOptions) {
opts.Prefix = true
}
// WithRev
type revOption struct {
rev int64
}
func WithRev(rev int64) interface {
GetOption
} {
return &revOption{
rev: rev,
}
}
func (o *revOption) SetGetOption(opts *getOptions) {
opts.Rev = o.rev
}
// Get
type getOptions struct {
Prefix bool
Rev int64
}
type GetOption interface {
SetGetOption(*getOptions)
}
func Get(key string, ops ...GetOption) {
opts := &getOptions{}
for _, op := range ops {
op.SetGetOption(opts)
}
fmt.Printf("Get got options: %+v\n", opts)
// do things...
}
// Delete
type deleteOptions struct {
Prefix bool
}
type DeleteOption interface {
SetDeleteOption(*deleteOptions)
}
func Delete(key string, ops ...DeleteOption) {
opts := &deleteOptions{}
for _, op := range ops {
op.SetDeleteOption(opts)
}
fmt.Printf("Delete got options: %+v\n", opts)
// do things...
}
func main() {
// Note how we can reuse `WithPrefix`
Get("sample_key", WithPrefix(), WithRev(1))
Delete("sample_key", WithPrefix())
// The following code won't compile since `Delete` doesn't accept `WithRev`
// Delete("sample_key", WithRev(1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment