Documentation ¶
Overview ¶
Package opt provides utilities for representing optional types.
While it is possible to represent an optional type in Go through the usage of a pointer, there are a number of drawbacks with such an approach:
- The value might be allocated on the heap due to the pointer reference.
- The value or structs of such values will not be comparable.
- It becomes unreadable when trying to represent an optional pointer type.
The generic type T in this package allows one to overcome the limitations of pointer references. Structs that are composed of such opt fields can often be safely used as map keys (as long as the underlying values are comparable).
Example ¶
package main import ( "fmt" "github.com/mokiat/gog/opt" ) func main() { type Search struct { Country opt.T[string] Age opt.T[int] } usersCache := make(map[Search][]string) usersCache[Search{ Country: opt.V("Bulgaria"), Age: opt.V(35), }] = []string{"John Doe", "Jane Doe"} users := usersCache[Search{ Country: opt.V("Bulgaria"), Age: opt.V(35), }] fmt.Printf("%#v\n", users) users = usersCache[Search{ Country: opt.V("Bulgaria"), Age: opt.Unspecified[int](), }] fmt.Printf("%#v\n", users) }
Output: []string{"John Doe", "Jane Doe"} []string(nil)
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type T ¶
type T[D any] struct { // Specified indicates whether Value can be used. Specified bool // Value holds the actual value. Value D }
T represents an optional type of generic type D.
func FromPtr ¶ added in v0.4.0
FromPtr returns an optional T value which is specified depending on whether the pointer can be dereferenced or not.
func Unspecified ¶
Unspecified returns an unspecified value of the generic type.
func (T[D]) ToPtr ¶ added in v0.4.0
func (t T[D]) ToPtr() *D
ToPtr returns a pointer-based representation of the value held in this optional. If this optional is not specified, then nil is returned.
func (T[D]) ValueOrDefault ¶ added in v0.13.0
func (t T[D]) ValueOrDefault(fallback D) D
ValueOrDefault returns the value held in this optional if it is specified, otherwise it returns the given fallback value.