This repository was archived by the owner on Aug 4, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4_unpack_example_test.go
More file actions
84 lines (70 loc) · 2.04 KB
/
4_unpack_example_test.go
File metadata and controls
84 lines (70 loc) · 2.04 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package mu_test
import (
"errors"
"fmt"
"github.com/appthrust/mu"
)
// ExampleResult_Unpack demonstrates converting Result back to Go's (value, error) pattern
func ExampleResult_Unpack() {
// Ok result unpacks to (value, nil)
okResult := mu.Ok(42)
value, err := okResult.Unpack()
fmt.Printf("Ok result: value=%d, err=%v\n", value, err)
// Err result unpacks to (zero_value, error)
errResult := mu.Err[int](errors.New("something went wrong"))
value, err = errResult.Unpack()
fmt.Printf("Err result: value=%d, err=%v\n", value, err)
// Output:
// Ok result: value=42, err=<nil>
// Err result: value=0, err=something went wrong
}
// ExampleResult_Unpack_withFunctions demonstrates using Unpack with functions
func ExampleResult_Unpack_withFunctions() {
// Function that returns Result
divide := func(a, b int) mu.Result[int] {
if b == 0 {
return mu.Err[int](errors.New("division by zero"))
}
return mu.Ok(a / b)
}
// Convert Result back to Go pattern for traditional error handling
handleDivision := func(a, b int) {
value, err := divide(a, b).Unpack()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Result: %d\n", value)
}
handleDivision(10, 2)
handleDivision(10, 0)
// Output:
// Result: 5
// Error: division by zero
}
// ExampleResult_Unpack_bridgeToLegacyCode shows bridging mu.Result to legacy Go code
func ExampleResult_Unpack_bridgeToLegacyCode() {
// Legacy function that expects (value, error)
processData := func(data string, err error) {
if err != nil {
fmt.Printf("Processing failed: %v\n", err)
return
}
fmt.Printf("Processing: %s\n", data)
}
// Modern function that returns Result
fetchData := func(id int) mu.Result[string] {
if id <= 0 {
return mu.Err[string](errors.New("invalid ID"))
}
return mu.Ok(fmt.Sprintf("data-%d", id))
}
// Bridge between modern and legacy code
data, err := fetchData(123).Unpack()
processData(data, err)
data, err = fetchData(-1).Unpack()
processData(data, err)
// Output:
// Processing: data-123
// Processing failed: invalid ID
}