This is a javascript style iterator sample using go. It's only a demo so don't expect too much from it.
I'm writing this to test whether it's possible to use goroutine to simulate generator without any issue. I take special care on memory issue. I use runtime.SetFinalizer
to make sure once it
is released all related goroutines will stop properly.
The result is quite good. It's promising.
And I also think of a way to declare generator function in go - using valid go syntax.
// Look at its return type.
// Unlike normal function, which return values at the end of function,
// generator function returns iterator and uses `yield` to exchange
// data. So the return type just contains types, no varaible name.
// The return type means:
// - `string iterator`: yield will send out string value to caller.
// - `int`: yield function will return int value from caller.
func SampleFunc(foo string) (string iterator, int) {
var i int
i = yield("first")
i = yield("second")
i = yield("third")
}
Of course, above code is not possible to pass go compiler. I'm planning to write a pre-compiler to generate correct code for me. What's the name of the pre-compiler? Rat, maybe.