Building a Flexible API
Apply the pattern.
Apply the Pattern
Now assemble the full pattern: a constructor that takes required arguments plus a variadic list of options.
The Variadic Constructor
Required parameters come first; options follow as ...Option.
package main
import "fmt"
type Server struct {
Host string
Port int
}
type Option func(*Server)
func WithPort(p int) Option { return func(s *Server) { s.Port = p } }
func NewServer(host string, opts ...Option) *Server {
s := &Server{Host: host}
for _, opt := range opts {
opt(s)
}
return s
}
func main() {
s := NewServer("localhost", WithPort(8080))
fmt.Printf("%+v\n", *s)
}All lessons in this course
- The Problem with Many Params
- Option Functions
- Building a Flexible API
- Defaults and Validation