|
1 | | -# go-optional |
| 1 | +# go-optional |
| 2 | + |
| 3 | + |
| 4 | +[](https://goreportcard.com/report/github.com/ghosind/go-optional) |
| 5 | +[](https://codecov.io/gh/ghosind/go-optional) |
| 6 | + |
| 7 | + |
| 8 | +[](https://pkg.go.dev/github.com/ghosind/go-optional) |
| 9 | + |
| 10 | +A container object to describe the specified type value that may or may not contain a non-nil value. |
| 11 | + |
| 12 | +## Installation |
| 13 | + |
| 14 | +You can install the package by the following command. |
| 15 | + |
| 16 | +```sh |
| 17 | +go get -u github.com/ghosind/go-optional |
| 18 | +``` |
| 19 | + |
| 20 | +## Getting Started |
| 21 | + |
| 22 | +You can create an `Optional` instance with a pointer, and perform actions with the `Optional` instance. |
| 23 | + |
| 24 | +```go |
| 25 | +s := "Hello world" |
| 26 | +vp := &s |
| 27 | + |
| 28 | +val = optional.New(vp) |
| 29 | +a.IsPresent() // true |
| 30 | +val.OrElse("default string") // Hello world |
| 31 | +val.IfPresent(func (s string) { |
| 32 | + fmt.Println(s) |
| 33 | +}) |
| 34 | +// Hello world |
| 35 | + |
| 36 | +// Optional instance with nil value |
| 37 | +vp = nil |
| 38 | +val := optional.New(vp) |
| 39 | +vp.IsPresent() // false |
| 40 | +val.OrElse("default string") // default string |
| 41 | +val.IfPresent(func (s string) { |
| 42 | + fmt.Println(s) |
| 43 | +}) // Not invoked |
| 44 | +``` |
| 45 | + |
| 46 | +The `Optional` type also supports marshaling the value to a JSON string, or unmarshal from a JSON string. |
| 47 | + |
| 48 | +```go |
| 49 | +type Example struct { |
| 50 | + Val *optional.Optional[string] `json:"val"` |
| 51 | +} |
| 52 | + |
| 53 | +example := Example{ |
| 54 | + Val: optional.Of("Hello world"), |
| 55 | +} |
| 56 | +out, err := json.Marshal(example) |
| 57 | +fmt.Println(string(out)) |
| 58 | +// {"val":"Hello world"} |
| 59 | + |
| 60 | +json.Unmarshal([]byte("Test"), &example) |
| 61 | +fmt.Println(example) |
| 62 | +// {Hello world} |
| 63 | +``` |
0 commit comments