github.com/enetx/g@v1.0.80/examples/monads/option.go (about)

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