generated from dogmatiq/template-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwithnamedexample_test.go
68 lines (59 loc) · 1.26 KB
/
withnamedexample_test.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
61
62
63
64
65
66
67
68
package imbue_test
import (
"context"
"fmt"
"github.com/dogmatiq/imbue"
)
// Color is a type that represents a color.
type Color string
type (
// Foreground is a name for a color.
Foreground imbue.Name[Color]
// Background is a name for a color.
Background imbue.Name[Color]
)
func ExampleByName() {
con := imbue.New()
defer con.Close()
// Declare a constructor for a Color named Foreground.
imbue.With0Named[Foreground](
con,
func(
ctx imbue.Context,
) (Color, error) {
return "<black>", nil
},
)
// Declare a constructor for a Color named Background.
imbue.With0Named[Background](
con,
func(
ctx imbue.Context,
) (Color, error) {
return "<white>", nil
},
)
// Invoke a function that depends on both the Foreground and Background
// colors.
err := imbue.Invoke2(
context.Background(),
con,
func(
ctx context.Context,
fg imbue.ByName[Foreground, Color],
bg imbue.ByName[Background, Color],
) error {
// Named dependencies have a Name() and Value() methods which return
// the name and value of the dependency.
fmt.Println(fg.Name(), "=", fg.Value())
fmt.Println(bg.Name(), "=", bg.Value())
return nil
},
)
if err != nil {
panic(err)
}
// Output:
// Foreground = <black>
// Background = <white>
}