https://github.com/heat1q/opt
Option type in Go
https://github.com/heat1q/opt
go golang option optional
Last synced: 4 months ago
JSON representation
Option type in Go
- Host: GitHub
- URL: https://github.com/heat1q/opt
- Owner: heat1q
- License: mit
- Created: 2022-04-20T13:40:46.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2022-04-21T17:53:51.000Z (about 3 years ago)
- Last Synced: 2025-01-13T04:16:48.783Z (6 months ago)
- Topics: go, golang, option, optional
- Language: Go
- Homepage:
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Option
[](https://pkg.go.dev/github.com/heat1q/opt)

[](https://goreportcard.com/report/github.com/heat1q/opt)
[](LICENSE.md)This package implements a Rust styled `Option` type for optional values in Go.
`Option` provides a wrapper around a value that may or may not be initialized
and a set of methods to extract the inner value or handle nil cases.## Usage
### Installation
```
go get -u github.com/heat1q/opt
```
### Example
```go
package mainimport (
"fmt""github.com/heat1q/opt"
)func main() {
o := opt.New("potato")
value, ok := o.Some()
fmt.Println(ok) // true
fmt.Println(value) // potato
}
```## Marshalling JSON
`Option` solves the nullable issue for values where the
default of a value is also considered valid. For instance, consider
the scenario where the `false` value of a `bool` is a valid instance of the nullable field.```go
package mainimport (
"fmt""github.com/heat1q/opt"
)type data struct {
Flag opt.Option[bool] `json:"flag,omitempty"`
}func main() {
var d data_ = json.Unmarshal(`{}`, &d)
_, ok := d.Value.Some()
fmt.Println(ok) // false
_ = json.Unmarshal(`{"flag": false}`, &d)
_, ok = d.Value.Some()
fmt.Println(ok) // true
}
```