Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.
package main
import("fmt""iter")// As long as the loop continues to run, yield will keep returning true,// indicating that more values exist.// However, if the loop terminates (for instance, due to a break or return),// yield will return false.// This allows to perform any necessary cleanup.funcgenerateFibonacci() iter.Seq[int]{returnfunc(yield func(int)bool){ a, b :=1,1for{if!yield(a){ fmt.Println("Stop sequence")return} a, b = b, a+b
}}}funcmain(){for v :=rangegenerateFibonacci(){ fmt.Println(v)if v >10{break}}}// $ go run main.go // 1// 1// 2// 3// 5// 8// 13// Stop sequence
A Golang iterator is a function that “yields” one result at a time, rather than computing an entire set of results and returning them all at once. When you use an iterator in a for loop with a range expression, the loop executes once for each value returned by the iterator. Here is an example of range over iterator in Go.