func(r *Result)Do(f fn) *Result { if r.Err != nil { return r } r.Data, r.Err = f(r.Data) return r }
funcmain() { data := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} filter1 := func(i interface{})(interface{}, error) { if i.(int) > 1 { return i, nil } returnnil, fmt.Errorf("little than 1: %v", i) } filter2 := func(i interface{})(interface{}, error) { if i.(int) > 4 { return i, nil } returnnil, fmt.Errorf("little than 4: %v", i) } filter3 := func(i interface{})(interface{}, error) { if i.(int)&1 == 0 { return i, nil } returnnil, fmt.Errorf("even number: %v", i) } c := make(chan *Result, 10) for _, d := range data { gofunc(d interface{}) { r := Result{ Data: d, Err: nil, } c <- r.Do(filter1).Do(filter2).Do(filter3) }(d) } for i := 0; i < 10; i++ { d := <-c if d.Err != nil { fmt.Println(d.Err.Error()) } else { fmt.Println(d.Data.(int)) } } }
// $ go run test.go // little than 4: 2 // 6 // even number: 7 // 8 // little than 4: 3 // little than 1: 0 // even number: 9 // little than 4: 4 // little than 1: 1 // even number: 5
funcmain() { data := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} filter1 := func(i interface{})(interface{}, error) { if i.(int) > 1 { return i, nil } returnnil, fmt.Errorf("little than 1: %v", i) } filter2 := func(i interface{})(interface{}, error) { if i.(int) > 4 { return i, nil } returnnil, fmt.Errorf("little than 4: %v", i) } filter3 := func(i interface{})(interface{}, error) { if i.(int)&1 == 0 { return i, nil } returnnil, fmt.Errorf("even number: %v", i) } c := make(chan *Result, 10) for _, d := range data { gofunc(d interface{}) { r := Result{ Data: d, Err: nil, } _ = r.Do(filter1) && r.Do(filter2) && r.Do(filter3) c <- &r }(d) } for i := 0; i < 10; i++ { d := <-c if d.Err != nil { fmt.Println(d.Err.Error()) } else { fmt.Println(d.Data.(int)) } } }
// $ go run test.go // 6 // even number: 7 // 8 // little than 1: 0 // little than 4: 3 // little than 4: 2 // little than 4: 4 // even number: 9 // little than 1: 1 // even number: 5