Created
January 9, 2024 00:13
-
-
Save austinhallett/85ae08a977c35a45bddaf48af0e28343 to your computer and use it in GitHub Desktop.
Builder pattern in Go
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
package main | |
import "fmt" | |
// Example object which may require optional arguments | |
type Server struct { | |
port int | |
host string | |
debug bool | |
} | |
// constructor for example object | |
func NewServer(options Options) *Server { | |
return &Server{ | |
port: options.Port, | |
host: options.Host, | |
debug: options.Debug, | |
} | |
} | |
// Object arguments | |
type Options struct { | |
Port int | |
Host string | |
Debug bool | |
} | |
// Builder functions | |
func (o Options) WithPort(port int) Options { | |
o.Port = port | |
return o | |
} | |
func (o Options) WithHost(host string) Options { | |
o.Host = host | |
return o | |
} | |
func (o Options) WithDebug(debug bool) Options { | |
o.Debug = debug | |
return o | |
} | |
// options constructor with defaults | |
func NewOptions() Options { | |
return Options{ | |
Port: 3000, | |
Host: "localhost", | |
Debug: false, | |
} | |
} | |
// example usage | |
func main() { | |
options := NewOptions(). | |
WithPort(8080). | |
WithHost("example.com"). | |
WithDebug(true) | |
server := NewServer(options) | |
fmt.Println(server) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment