gopt

package module
v0.0.0-...-1542532 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2023 License: MIT Imports: 0 Imported by: 0

README

gopt

Go Reference

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

  1. 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:

  2. 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

Overview

Example
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}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply[T any](x T, options ...Option[T]) T

Apply applies all options to x.

Types

type Option

type Option[T any] func(x T)

Option sets an optional parameter for x.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL