Skip to content

Commit 472de8a

Browse files
committed
docs: update readme.
1 parent 605ace8 commit 472de8a

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

README.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,63 @@
1-
# go-optional
1+
# go-optional
2+
3+
![test](https://github.com/ghosind/go-optional/workflows/test/badge.svg)
4+
[![Go Report Card](https://goreportcard.com/badge/github.com/ghosind/go-optional)](https://goreportcard.com/report/github.com/ghosind/go-optional)
5+
[![codecov](https://codecov.io/gh/ghosind/go-optional/branch/main/graph/badge.svg)](https://codecov.io/gh/ghosind/go-optional)
6+
![Version Badge](https://img.shields.io/github/v/release/ghosind/go-optional)
7+
![License Badge](https://img.shields.io/github/license/ghosind/go-optional)
8+
[![Go Reference](https://pkg.go.dev/badge/github.com/ghosind/go-optional.svg)](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

Comments
 (0)