Created
July 9, 2014 12:29
-
-
Save voldyman/09cd222814da29cc71ea to your computer and use it in GitHub Desktop.
The Golang's range operator is limited to a few times, this example allows you to iterate over custom collections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Container struct { | |
values []int | |
} | |
func (this *Container) Iter() <- chan int { | |
ch := make(chan int) | |
go func() { | |
for _, el := range this.values { | |
ch <- el | |
} | |
close(ch) | |
}() | |
return ch | |
} | |
func main() { | |
fmt.Println("Hello, playground") | |
a := &Container{ | |
values: []int{1, 2, 3, 9, 8, 7, 6, 5, 4}, | |
} | |
for el := range a.Iter() { | |
fmt.Println(el) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment