Beware . As deft_code is mentioned, this code leaks out the channel and goroutine when the loop breaks. Do not use this as a general template.
There is no way in go to make an arbitrary type compatible with range , since range only supports slices, arrays, channels, and maps.
You can iterate through the channels using range , which is useful if you want to iterate over dynamically generated data without the need to use a slice or an array.
For instance:
func Iter() chan *Friend { c := make(chan *Friend) go func() { for i:=0; i < 10; i++ { c <- newFriend() } close(c) }() return c } func main() {
What is the closest thing you need to do to make something "affordable."
So, itβs common practice to define an Iter() method or something similar by type and go to range .
See the specification for further reading on range .
source share