-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
60 lines (47 loc) · 1.46 KB
/
option.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"fmt"
"strconv"
"github.com/enetx/g"
)
func main() {
// Creating Some and None Options
someOption := g.Some(42)
noneOption := g.None[int]()
// Checking if Option is Some or None
fmt.Println(someOption.IsSome()) // Output: true
fmt.Println(noneOption.IsNone()) // Output: true
// Unwrapping Options
fmt.Println(someOption.Unwrap()) // Output: 42
fmt.Println(noneOption.UnwrapOr(10)) // Output: 10
// Mapping over Options
doubledOption := someOption.Then(func(val int) g.Option[int] {
return g.Some(val * 2)
})
fmt.Println(doubledOption.Unwrap()) // Output: 84
// Using OptionMap to transform the value inside Option
addTwoOption := g.OptionMap(someOption, func(val int) g.Option[string] {
return g.Some("result: " + strconv.Itoa(val+2))
})
fmt.Println(addTwoOption.Unwrap()) // Output: "result: 44"
// Using UnwrapOrDefault to handle None Option with default value
defaultValue := noneOption.UnwrapOrDefault()
fmt.Println(defaultValue) // Output: 0 (default value for int)
// Using Then to chain operations on Option
resultOption := someOption.
Then(
func(val int) g.Option[int] {
if val > 10 {
return g.Some(val * 2)
}
return g.None[int]()
}).
Then(
func(val int) g.Option[int] {
return g.Some(val + 5)
})
fmt.Println(resultOption.Unwrap()) // Output: 89
// Using Expect to handle None Option
noneOption.Expect("This is None")
// The above line will panic with message "This is None"
}