Skip to content

adolfo/optional-go

Repository files navigation

Optional Gopher

Optional Go

Tests License

Library for conveniently and safely dealing with optional (nullable) values.

Note: Requires Go 1.18 with generics support.

Installation

$ go get github.com/adolfo/optional-go

Usage

package main

import (
    "github.com/adolfo/optional-go"
)

Initialization with literal values

// Optional string
optStr := optional.Of("foo")

// Optional int
optInt := optional.Of(5)

// Optional float64
optFlt := optional.Of(9.99)

// Optional struct
type Thing struct {
    foo int
    bar string
}
optThing := optional.Of(Thing{42, "baz"})

Initialization with nil values

// Optional string with nil value
nilStr := optional.OfNil[string]()

// Optional int with nil value
nilInt := optional.OfNil[int]()

// Nil struct
nilThg := optional.OfNil[Thing]()

Alternative initialization with nil values

// Optional int with nil value
var nilInt optional.Value[int]

// Optional string with nil value
nilStr := optional.Value[string]{}

Updating optional values

o := optional.OfNil[int]

// Set new value
o.Set(42)

// Clearing value and resetting to nil
o.SetNil()

// Set invalid value
o.Set("fred") // compiler error; type is Optional.Value[int]

Getting optional values

o := optional.Of(42)

// Safely get underlying optional value
if ok, val := o.Get(); ok {
    fmt.Println(val) // prints 42
}

// Unsafely get value
fmt.Println(o.MustGet()) // prints 42
o.SetNil()
fmt.Println(o.MustGet()) // panics

Get value with default

o := optional.Of("foo")

fmt.Println(o.GetOr("fred")) // prints "foo"

o.SetNil()
fmt.Println(o.GetOr("fred")) // prints "fred"

Checking for value

if o.HasValue() {
    fmt.Println("has value")
}

if o.IsNil() {
    fmt.Println("value is nil")
}

JSON Marshaling & Unmarshaling

type Person struct {
    Name optional.Value[string] `json:"name"`
    Age  optional.Value[int]    `json:"age"`
}

j := `{ "name": null, "age": 42 }`
p := new(Person)
json.Unmarshal([]byte(j), p)

fmt.Println("name is %s", p.Name.GetOr("Unknown"))
// prints "name is Unknown" since `name` was null

License

Released under the MIT License

About

Optional wrapper for Go types

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages