goptional

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2022 License: MIT Imports: 0 Imported by: 0

README

Go Optional

POC Go generic implementation inspired by Java Optional.

Requires Go 1.18.

Examples

None and Some
none := None[bool]()
some := Some(42)

// check if the value is empty
none.IsEmpty()          // true
some.IsEmpty()          // false

// check if the value is present
none.IsPresent()        // false
some.IsPresent()        // true

// Get gives back the value and ok is true if it's present
val, ok := none.Get()   // val = false, ok = false
val, ok := some.Get()   // val = 42, ok = true

// get the value with default
none.GetOr(true)        // true
some.GetOr(100)         // 42

// get the value or the types zero value
none.GetOrZero()     // false
some.GetOrZero()     // 42

// GetOrPanic will panic if value is not present
none.GetOrPanic()       // will panic
some.GetOrPanic()       // 42

// IfPresent will run the callback if the value is present
none.IfPresent(func(val bool) { // noop
    // will never run
})
some.IfPresent(func(val int) {  // will print 42
    println(val)
})
Of
val := 42
var p *int

Of(&val)).IsPresent()  // true
Of(p)).IsPresent()     // false

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func None

func None[T any]() optional[T]

func Of

func Of[T any](val *T) optional[T]

func Some

func Some[T any](val T) optional[T]

Types

This section is empty.

Jump to

Keyboard shortcuts

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