https://github.com/teivah/goptional
A lightweight library to provide a container for optional values in golang
https://github.com/teivah/goptional
Last synced: 6 months ago
JSON representation
A lightweight library to provide a container for optional values in golang
- Host: GitHub
- URL: https://github.com/teivah/goptional
- Owner: teivah
- License: apache-2.0
- Created: 2018-02-11T16:05:08.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2018-02-12T08:26:29.000Z (over 7 years ago)
- Last Synced: 2025-03-19T09:14:33.105Z (7 months ago)
- Language: Go
- Homepage:
- Size: 11.7 KB
- Stars: 32
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://goreportcard.com/report/gojp/goreportcard)
goptional is a lightweight library to provide a container for optional values in golang.
## Initialization
```go
// Create an optional with an initial value
opt, _ := optional.Of(5)// An optional created with a nil value returns an error
_, err := optional.Of(nil)// Create an empty optional
opt := optional.OfEmpty()
```### Nil pointer
```go
var nilPointer *int
_, err := Of(nilPointer) // err is not nil
```### Nil array
```go
nilArray := [3]int{}
_, err := Of(nilArray) // err is not nil
```### Nil slice
```go
var nilSlice []int
_, err := Of(nilSlice) // err is not nil
```### Nil map
```go
var nilMap map[int]int
_, err := Of(nilMap) // err is not nil
```### Nil function
```go
var nilFunction func()
_, err := Of(nilFunction) // err is not nil
```### Nil structure
```go
type Point struct {
x, y int
}
var emptyPoint Point
_, err = Of(emptyPoint) // err is nil
```## Features
```go
// Get its value and an eventual error if the optional is empty
v, err := opt.Get()// Get the optional value regardless of its emptiness
v := opt.GetValue()// Test if the optional is not empty
opt.IsPresent()// Execute a function if the optional is not empty
opt.IfPresent(f)// Execute a function if the optional is empty
opt.IfNotPresent(f)// Returns an error if the optional is not empty (otherwise returns a nil value)
err := opt.IfPresentError(errors.New("present")// Returns an error if the optional is empty (otherwise returns a nil value)
err := opt.IfNotPresentError(errors.New("not present")// Panic if the optional is not empty
opt.IfPresentPanic("present")// Panic if the optional is empty
opt.IfNotPresentPanic("not present")
```