ghosind / go-optional

A container object to describe the specified type value that may or may not contain a non-nil value.

Home Page:https://pkg.go.dev/github.com/ghosind/go-optional

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

go-optional

test Go Report Card codecov Version Badge License Badge Go Reference

A container object to describe the specified type value that may or may not contain a non-nil value.

Installation

You can install the package by the following command.

go get -u github.com/ghosind/go-optional

Getting Started

You can create an Optional instance with a pointer, and perform actions with the Optional instance.

s := "Hello world"
vp := &s

val = optional.New(vp)
a.IsPresent() // true
val.OrElse("default string") // Hello world
val.IfPresent(func (s string) {
  fmt.Println(s)
})
// Hello world

// Optional instance with nil value
vp = nil
val := optional.New(vp)
vp.IsPresent() // false
val.OrElse("default string") // default string
val.IfPresent(func (s string) {
  fmt.Println(s)
}) // Not invoked

The Optional type also supports marshaling the value to a JSON string, or unmarshal from a JSON string.

type Example struct {
  Val *optional.Optional[string] `json:"val"`
}

example := Example{
  Val: optional.Of("Hello world"),
}
out, err := json.Marshal(example)
fmt.Println(string(out))
// {"val":"Hello world"}

json.Unmarshal([]byte("Test"), &example)
fmt.Println(example)
// {Hello world}

About

A container object to describe the specified type value that may or may not contain a non-nil value.

https://pkg.go.dev/github.com/ghosind/go-optional

License:MIT License


Languages

Language:Go 100.0%