Skip to content

Commit 4980685

Browse files
committed
doc: add usage examples
Closes TNTP-3732
1 parent 980ba0a commit 4980685

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
lines changed

README.md

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ with optional values:
6464

6565
```go
6666
// Create an optional with a value.
67-
opt := SomeOptionalString("hello")
67+
opt := option.SomeString("hello")
6868

6969
// Check if a value is present.
7070
if opt.IsSome() {
@@ -79,6 +79,30 @@ value := opt.UnwrapOr("default")
7979
err := opt.EncodeMsgpack(encoder)
8080
```
8181

82+
### Using generic approach
83+
84+
```go
85+
type SomeType struct {
86+
name string
87+
number int
88+
}
89+
90+
// Create an optional with a value.
91+
opt := option.Some(SomeType{"hello", 42})
92+
93+
// Check if a value is present.
94+
if opt.IsSome() {
95+
value := opt.Unwrap()
96+
fmt.Println(value)
97+
}
98+
99+
// Use a default value if none.
100+
value := opt.UnwrapOr(SomeType{"default", 0})
101+
102+
// Encode to MessagePack.
103+
err := opt.EncodeMsgpack(encoder)
104+
```
105+
82106
### Usage with go-tarantool
83107

84108
It may be necessary to use an optional type in a structure. For example,
@@ -147,7 +171,7 @@ while ensuring proper encoding and decoding when using MessagePack.
147171
- `SomeXxx(value)` - Create an optional with a value
148172
- `NoneXxx()` - Create an empty optional
149173
- `Unwrap()`, `UnwrapOr()`, `UnwrapOrElse()` - Value extraction
150-
- `IsSome()`, `IsNone()` - Presence checking
174+
- `IsSome()`, `IsNil()` - Presence checking
151175
- Full MessagePack `CustomEncoder` and `CustomDecoder` implementation
152176
- Type-safe operations
153177

@@ -240,12 +264,13 @@ For example, to generate an optional type for `github.com/google/uuid.UUID`:
240264

241265
### Using Generated Types
242266

243-
Generated types follow the pattern Optional<TypeName> and provide methods for working
244-
with optional values:
267+
Generated types provide methods for working with optional values and 2 constructors for every single type:
268+
`Some<TypeName>` creates option with some value and `None<TypeName>` creates the empty one
269+
(<TypeName> is the original type name started with upper case):
245270

246271
```go
247272
// Create an optional with a value.
248-
opt := SomeOptionalString("hello")
273+
opt := option.SomeString("hello")
249274
250275
// Check if a value is present.
251276
if opt.IsSome() {
@@ -329,7 +354,7 @@ At this point we can see already that the alternatives (based on pointer and sli
329354
330355
Now let's check encoding and decoding.
331356
332-
## Encode + Decode
357+
#### Encode + Decode
333358
334359
```
335360
# int

0 commit comments

Comments
 (0)