Skip to content

go-andiamo/gopt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Gopt

GoDoc Latest Version codecov Go Report Card

A very light Optional implementation in Golang

Installation

To install Gopt, use go get:

go get github.com/go-andiamo/gopt

To update Gopt to the latest version, run:

go get -u github.com/go-andiamo/gopt

Examples

package main

import (
    . "github.com/go-andiamo/gopt"
)

func main() {
    optFlt := Of[float64](1.23)
    println(optFlt.IsPresent())
    println(optFlt.OrElse(-1))

    opt2 := Empty[float64]()
    println(opt2.IsPresent())
    println(opt2.OrElse(-1))

    opt2.OrElseSet(10)
    println(opt2.IsPresent())
    println(opt2.OrElse(-1))
}

try on go-playground

Optionals can also be very useful when used in conjunction with JSON unmarshalling - to determine whether unmarshalled properties were actually present, with a valid value, in the JSON. The following code demonstrates...

package main

import (
    "encoding/json"
    "fmt"

    . "github.com/go-andiamo/gopt"
)

type NormalStruct struct {
    Foo string
    Bar int
    Baz float64
}

type OptsStruct struct {
    Foo Optional[string]
    Bar Optional[int]
    Baz Optional[float64]
}

func main() {
    jdata := `{"Foo": null, "Bar": 1}`

    normal := &NormalStruct{}
    err := json.Unmarshal([]byte(jdata), normal)
    if err == nil {
        // was property Foo set???
        fmt.Printf("'Foo' was set to \"%s\"???\n", normal.Foo) // was it really?
        // was property Bar actually set to 0???
        fmt.Printf("'Bar' was set to \"%d\"???\n", normal.Bar) // was it really?
        // was property Baz actually set to 0.000???
        fmt.Printf("'Baz' was set to \"%f\"???\n", normal.Baz) // was it really?
    } else {
        println(err.Error())
    }

    println()
    // now try with optionals...
    opts := &OptsStruct{}
    err = json.Unmarshal([]byte(jdata), opts)
    if err == nil {
        opts.Foo.IfSetOtherwise(
            func(v string) {
                fmt.Printf("'Foo' was set to \"%s\"\n", v)
            },
            func() {
                println("'Foo' was set but not to a valid value")
            },
            func() {
                println("'Foo' was not set at all")
            },
        )
        opts.Bar.IfSetOtherwise(
            func(v int) {
                fmt.Printf("'Bar' was set to %d\n", v)
            },
            func() {
                println("'Bar' was set but not to a valid value")
            },
            func() {
                println("'Bar' was not set at all")
            },
        )
        opts.Baz.IfSetOtherwise(
            func(v float64) {
                fmt.Printf("'Baz' was set to %f\n", v)
            },
            func() {
                println("'Baz' was set but not to a valid value")
            },
            func() {
                println("'Baz' was not set at all")
            },
        )
    } else {
        println(err.Error())
    }
}

try on go-playground

Methods

Method and description Returns
AsEmpty()
returns a new empty optional of the same type
*Optional[T]
Clear()
clears the optional
Clearing sets the present to false, the set flag to false and the value to an empty value
*Optional[T]
Default(v T)
returns the value if present, otherwise returns the provided default value
T
Filter(f func(v T) bool)
if the value is present and calling the supplied filter function returns true, returns a new optional describing the value
Otherwise returns an empty optional
*Optional[T]
Get()
returns the value and an error if the value is not present
(T, error)
GetOk()
returns the value and true if the value is present
otherwise returns an empty value and false
(T, bool)
IfElse(condition bool, other T)
if the supplied condition is true and the value is present, returns the value
otherwise the other value is returned
T
IfPresent(f func(v T))
if the value is present, calls the supplied function with the value, otherwise does nothing
returns the original optional
*Optional[T]
IfPresentOtherwise(f func(v T), other func())
if the value is present, calls the supplied function with the value, otherwise calls the other function
returns the original optional
*Optional[T]
IfSet(f func(v T), notPresent func())
if the value was set and is present, calls the supplied function with the value
if the value was set but is not present, calls the supplied notPresent function
otherwise, does nothing
returns the original optional
*Optional[T]
IfSetOtherwise(f func(v T), notPresent func(), other func())
if the value was set and is present, calls the supplied function with the value
if the value was set but is not present, calls the supplied notPresent function
otherwise, calls the other func
returns the original optional
*Optional[T]
IsPresent()
returns true if the value is present, otherwise false
bool
Map(f func(v T) any)
if the value is present and the result of calling the supplied mapping function returns non-nil, returns an optional describing that returned value
Otherwise returns an empty optional
*Optional[any]
MarshalJSON()
implements JSON marshal
if the value is present, returns the marshalled data for the value
Otherwise, returns the marshalled data for null
([]byte, error)
OrElse(other T)
returns the value if present, otherwise returns other
T
OrElseError(err error)
returns the supplied error if the value is not present, otherwise returns nil
error
OrElseGet(f func() T)
returns the value if present, otherwise returns the result of calling the supplied function
T
OrElsePanic(v any)
if the value is not present, panics with the supplied value, otherwise does nothing
returns the original optional
*Optional[T]
OrElseSet(v T)
if the value is not present it is set to the supplied value
*Optional[T]
Scan(value interface{})
implements sql.Scan
error
UnSet()
clears the set flag (see WasSet())
returns the original optional
*Optional[T]
UnmarshalJSON(data []byte)
implements JSON unmarshal
if the supplied data is null representation, sets the present to false
Otherwise, unmarshal the data as the value and sets the optional to present (unless the result of unmarshalling the value returns an error - in which case the present is set to false)
error
WasSet()
returns true if the last setting operation set the value, otherwise false
Setting operations are UnmarshalJSON(), Scan() and OrElseSet()
Use method UnSet() to clear this flag alone
bool
WasSetElse(other T)
returns the value if present and set, otherwise returns other
T
WasSetElseError(err error)
returns the supplied error if the value is not present and set, otherwise returns nil
if the supplied error is nil and the value is not present and set, a NotPresentError is returned
error
WasSetElseGet(f func() T)
returns the value if present and set, otherwise returns the result of calling the supplied function
if the supplied function is nil and the value is not present and set, returns a default empty value
T
WasSetElsePanic(v any)
if the value is not present and set, panics with the supplied value, otherwise does nothing
returns the original optional
*Optional[T]
WasSetElseSet(v T)
if the value is not present and set it is set to the value supplied
*Optional[T]

Constructors

Constructor function and description
Of[T any](value T) *Optional[T]
Creates a new optional with the supplied value
OfNillable[T any](value T) *Optional[T]
Creates a new optional with the supplied value
If the supplied value is nil, an empty (not present) optional is returned
OfNillableString(value string) *Optional[string]
Creates a new string optional with the supplied value
If the supplied value is an empty string, an empty (not-present) optional is returned
Empty[T any]() *Optional[T]
Creates a new empty (not-present) optional of the specified type
EmptyString() *Optional[string]
returns an empty optional of type string
EmptyInterface() *Optional[interface{}]
returns an empty optional of type interface{}
EmptyInt() *Optional[int]
returns an empty optional of type int
EmptyInt8() *Optional[int8]
returns an empty optional of type int8
EmptyInt16() *Optional[int16]
returns an empty optional of type int16
EmptyInt32() *Optional[int32]
returns an empty optional of type int32
EmptyInt64() *Optional[int64]
returns an empty optional of type int64
EmptyUint() *Optional[uint]
returns an empty optional of type uint
EmptyUint8() *Optional[uint8]
returns an empty optional of type uint8
EmptyUint16() *Optional[uint16]
returns an empty optional of type uint16
EmptyUint32() *Optional[uint32]
returns an empty optional of type uint32
func EmptyUint64() *Optional[uint64]
returns an empty optional of type uint64
EmptyBool() *Optional[bool]
returns an empty optional of type bool
EmptyFloat32() *Optional[float32]
returns an empty optional of type float32
EmptyFloat64() *Optional[float64]
returns an empty optional of type float64
EmptyByte() *Optional[byte]
returns an empty optional of type byte
EmptyRune() *Optional[rune]
returns an empty optional of type rune