added iterator example

This commit is contained in:
jian.han 2018-01-24 17:18:41 +10:00
parent d1e5d3f1c1
commit 87e8b9e074

View File

@ -1,6 +1,7 @@
package main
import (
"fmt"
"time"
"github.com/davecgh/go-spew/spew"
@ -21,7 +22,44 @@ func dummyFetchUrl(url string) *FetchResult {
}
}
func main() {
r := dummyFetchUrl("http://www.google.com")
spew.Dump(r)
func concurrentFetch(urls []string) <-chan *FetchResult {
rChan := make(chan *FetchResult, len(urls))
for _, url := range urls {
go func(url string) {
result := dummyFetchUrl(url)
rChan <- result
}(url)
}
return rChan
}
func main() {
// mock the urls
urls := []string{
"test1",
"test2",
"test3",
"test4",
"test5",
"test6",
}
// this is a prefered method
chanResults := concurrentFetch(urls)
for i := 0; i < len(urls); i++ {
select {
case c := <-chanResults:
spew.Dump(c)
}
}
// i := 0
// for v := range concurrentFetch(urls) {
// spew.Dump(i, v)
// i++
// if i == len(urls) {
// break
// }
// }
fmt.Println("All my things are done")
}