package
module
Version:
v0.0.0-...-1542532
Opens a new window with list of versions in this module.
Published: May 8, 2023
License: MIT
Opens a new window with license information.
Imports: 0
Opens a new window with list of imports.
Imported by: 0
Opens a new window with list of known importers.
README
¶
gopt

Generic Functional Options for Go.
Installation
$ go get -u github.com/RussellLuo/gopt
Quick Start
package main
import (
"fmt"
"github.com/RussellLuo/gopt"
)
type Server struct {
host string
port int
}
func New(options ...gopt.Option[*Server]) *Server {
return gopt.Apply(new(Server), options...)
}
// ServerOption holds all option factories for Server.
type ServerOption struct{}
func (ServerOption) Host(host string) gopt.Option[*Server] {
return func(s *Server) { s.host = host }
}
func (ServerOption) Port(port int) gopt.Option[*Server] {
return func(s *Server) { s.port = port }
}
func main() {
server := New(
ServerOption{}.Host("localhost"),
ServerOption{}.Port(8080),
)
fmt.Printf("server: %+v\n", server)
// Output:
// server: &{host:localhost port:8080}
}
FAQ
-
Why might I want to use this tiny library?
Traditional Functional Options will define many exported functions, which is likely to cause naming conflicts.
Reference articles:
Reference projects:
-
Why is ServerOption{} used in the example?
ServerOption is a named alias of the empty struct, whose instances are fungible and consume no space.
Unsafe gopt
Unsafe gopt is an early implementation, which is deprecated and for reference only.
License
MIT
Documentation
¶
package main
import (
"fmt"
"github.com/RussellLuo/gopt"
)
type Server struct {
host string
port int
}
func New(options ...gopt.Option[*Server]) *Server {
return gopt.Apply(new(Server), options...)
}
// ServerOption holds all option factories for Server.
type ServerOption struct{}
func (ServerOption) Host(host string) gopt.Option[*Server] {
return func(s *Server) { s.host = host }
}
func (ServerOption) Port(port int) gopt.Option[*Server] {
return func(s *Server) { s.port = port }
}
func main() {
server := New(
ServerOption{}.Host("localhost"),
ServerOption{}.Port(8080),
)
fmt.Printf("server: %+v\n", server)
}
Output:
server: &{host:localhost port:8080}
func Apply[T any](x T, options ...Option[T]) T
Apply applies all options to x.
type Option[T any] func(x T)
Option sets an optional parameter for x.
Source Files
¶
Click to show internal directories.
Click to hide internal directories.