Skip to content
/ opt Public

Golang library for optional types

License

ifnotnil/opt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

25 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

opt

CI Status codecov Go Report Card PkgGoDev

Install: go get -u github.com/ifnotnil/opt

Golang generic optional type with support for json.Marshaler, json.Unmarshaler, driver.Valuer, sql.Scanner and golang 1.24 json omitzero tag.

The main ideas are:

  • Separate present-but-nil from not present (e.g., for the HTTP PATCH method).
  • Implement optional values without using pointers.

States

State Constructor function Description
None None[T]() Value is absent, not preset nor nil.
Nil Nil[T]() Value is present but nil
Valid New[T](t T) Value is preset and valid (not nil)

Json unmarshaling

Given a struct

type Foo struct {
	A Optional[int] `json:"a"`
}
Json Resulted state of A
{} None
{"a": null} Nil
{"a": 123} Valid

Why not Set?

We can achieve that by writing the optional value using one of the constructor functions.

a := Nil["string")
// ...

a = New("test")

About

Golang library for optional types

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •