Skip to content

markphelps/optional

1.18
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Code
This branch is 8 commits ahead, 6 commits behind main.

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Optional

Build Status Release Software License Go Doc Go Report Card SayThanks.io

Optional is a library that provides option types for Go using generics.

Motivation

In Go, variables declared without an explicit initial value are given their zero value. Most of the time this is what you want, but sometimes you want to be able to tell if a variable was set or if it's just a zero value. That's where option types come in handy.

Inspiration

Usage

package main

import (
    "fmt"

    "github.com/markphelps/optional"
)

func main() {
    s := optional.New("foo")

    value, err := s.Get()
    if err != nil {
        // handle error!
    } else {
        fmt.Println(value)
    }

    t := optional.Optional[string]{}
    fmt.Println(t.OrElse("bar"))
}

See example_test.go and the documentation for more usage.

Marshalling/Unmarshalling JSON

Note: v0.6.0 introduces a potential breaking change to anyone depending on marshalling non-present values to their zero values instead of null. See: #9 for more context.

Option types marshal to/from JSON as you would expect:

Marshalling

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var value = struct {
        Field optional.Optional[string] `json:"field,omitempty"`
    }{
        Field: optional.New("bar"),
    }

    out, _ := json.Marshal(value)

    fmt.Println(string(out))
    // outputs: {"field":"bar"}
}

Unmarshalling

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var value = &struct {
        Field optional.Optional[string] `json:"field,omitempty"`
    }{}

    _ = json.Unmarshal([]byte(`{"field":"bar"}`), value)

    value.Field.If(func(s string) {
        fmt.Println(s)
    })
    // outputs: bar
}

See example_test.go for more examples.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request