diff --git a/example_test.go b/example_test.go index 4471957..41e6c00 100644 --- a/example_test.go +++ b/example_test.go @@ -1296,7 +1296,6 @@ func ExampleQuery_Take() { fmt.Printf("The top three grades are: %v", topThreeGrades) // Output: // The top three grades are: [98 92 85] - } // The following code example demonstrates how to use TakeWhile @@ -1354,6 +1353,22 @@ func ExampleQuery_ToChannel() { // 10 } +// The following code example demonstrates how to use ToChannelT +// to send a slice to a typed channel. +func ExampleQuery_ToChannelT() { + c := make(chan string) + + go Repeat("ten", 3).ToChannelT(c) + + for i := range c { + fmt.Println(i) + } + // Output: + // ten + // ten + // ten +} + // The following code example demonstrates how to use ToMap to populate a map. func ExampleQuery_ToMap() { type Product struct { diff --git a/result.go b/result.go index 34e47ab..588cbd5 100644 --- a/result.go +++ b/result.go @@ -544,6 +544,22 @@ func (q Query) ToChannel(result chan<- interface{}) { close(result) } +// ToChannelT is the typed version of ToChannel. +// +// - result is of type "chan TSource" +// +// NOTE: ToChannel has better performance than ToChannelT. +func (q Query) ToChannelT(result interface{}) { + r := reflect.ValueOf(result) + next := q.Iterate() + + for item, ok := next(); ok; item, ok = next() { + r.Send(reflect.ValueOf(item)) + } + + r.Close() +} + // ToMap iterates over a collection and populates result map with elements. // Collection elements have to be of KeyValue type to use this method. To // populate a map with elements of different type use ToMapBy method. ToMap diff --git a/result_test.go b/result_test.go index c4899e2..8faeb6d 100644 --- a/result_test.go +++ b/result_test.go @@ -464,6 +464,22 @@ func TestToChannel(t *testing.T) { } } +func TestToChannelT(t *testing.T) { + c := make(chan string) + input := []string{"1", "2", "3", "4", "5"} + + go From(input).ToChannelT(c) + + result := []string{} + for value := range c { + result = append(result, value) + } + + if !reflect.DeepEqual(result, input) { + t.Errorf("From(%v).ToChannelT()=%v expected %v", input, result, input) + } +} + func TestToMap(t *testing.T) { input := make(map[int]bool) input[1] = true