Skip to content

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

License

Notifications You must be signed in to change notification settings

ghosind/go-optional

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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}