-
Notifications
You must be signed in to change notification settings - Fork 5
/
future.go
65 lines (52 loc) · 1.01 KB
/
future.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
package main
import "fmt"
import "sync"
import "errors"
import "math/rand"
import "time"
type SuccessFunc func(string)
type FailureFunc func(error)
type ExecuteFunc func(int) (string, error)
type Subject struct {
success SuccessFunc
failure FailureFunc
}
func (s *Subject) Success(f SuccessFunc) *Subject {
s.success = f
return s
}
func (s *Subject) Failure(f FailureFunc) *Subject {
s.failure = f
return s
}
func (s *Subject) Execute(f ExecuteFunc) {
var wg sync.WaitGroup
wg.Add(1)
go func(s *Subject) {
r := rand.NewSource(time.Now().UnixNano())
n := rand.New(r)
str, err := f(n.Intn(200))
if err != nil {
s.failure(err)
wg.Done()
} else {
s.success(str)
wg.Done()
}
}(s)
wg.Wait()
}
func main() {
s := Subject{}
s.Success(func(m string) {
fmt.Println("SUCCESS: ", m)
}).Failure(func(e error) {
fmt.Println("FAILURE: ", e)
}).Execute(func(num int) (string, error) {
if num < 100 {
return "", errors.New("too low number")
} else {
return "valid number", nil
}
})
}