Created
September 26, 2019 13:37
-
-
Save kamal-github/0be145c1d1a40849e9e2e40e2a778804 to your computer and use it in GitHub Desktop.
Go Visitor Pattern to pass and apply options
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
type Logger struct { | |
Prop1 string | |
Prop2 string | |
} | |
type Option func(l *Logger) error | |
func Prop1Option() Option { | |
return func(l *Logger) error { | |
l.Prop1 = "hello" | |
return nil | |
} | |
} | |
func Prop2Option(w string) Option { | |
return func(l *Logger) error { | |
l.Prop1 = w | |
return nil | |
} | |
} | |
func (l *Logger) SetOptions(opts ...Option) error { | |
for _, applyOptTo := range opts { | |
if err := applyOptTo(l); err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
func testing() { | |
l := new(Logger) | |
err := l.SetOptions(Prop1Option(), Prop2Option("world")) | |
log.Error(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment