Generators
Demonstrates lazy sequence generation; Go approximates it with channels plus goroutines, Java with Streams, Rust with iterators.
C C23
#include <stdio.h>
// C has no yield; hand-write a generator as a "stateful iteration function": each call produces one value
int count_to_next(int n, int *state) {
if (*state < n) {
return ++*state;
}
return -1; // iteration-end marker
}
int main(void) {
int state = 0;
int v;
while ((v = count_to_next(3, &state)) != -1) {
printf("%d\n", v);
}
return 0;
}
1 2 3
C++ C++26
#include <iostream>
// before C++20 co_yield, the idiom is a hand-written generator class: keep state, lazily produce in next()
class CountTo {
public:
explicit CountTo(int n) : n_(n) {}
bool next(int &out) { // returning false marks the end of iteration
if (cur_ >= n_) return false;
out = ++cur_;
return true;
}
private:
int n_;
int cur_ = 0;
};
int main() {
CountTo g(3); // creation performs no computation: values are produced step by step during iteration (lazy)
int v;
while (g.next(v)) {
std::cout << v << "\n";
}
return 0;
}
1 2 3
C# v11.0.100
// yield return: produces one value then pauses, lazy execution (compiler-generated state machine)
IEnumerable<int> CountTo(int n) {
for (var i = 1; i <= n; i++) {
yield return i;
}
}
foreach (var v in CountTo(3)) { // executes step by step during iteration
Console.WriteLine(v);
}
1 2 3
Go v1.27.4
package main
import "fmt"
// Go has no yield syntax: a goroutine + channel achieves lazy production
func countTo(n int) <-chan int {
ch := make(chan int)
go func() {
for i := 1; i <= n; i++ {
ch <- i // the consumer takes one, then production resumes (backpressure)
}
close(ch)
}()
return ch
}
func main() {
for v := range countTo(3) { // range keeps receiving until the channel closes
fmt.Println(v)
}
}
1 2 3
Java v27.0.1
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
// Java has no generator syntax; intermediate Stream operations are lazy:
// they run only when a terminal operation (forEach/collect) is reached
IntStream.rangeClosed(1, 3)
.map(i -> i * 10)
.forEach(System.out::println);
}
}
10 20 30
JavaScript v26.13.1
// function* defines a generator function: yield produces lazily
function* countTo(n) {
for (let i = 1; i <= n; i++) {
yield i;
}
}
for (const v of countTo(3)) { // the generator object implements the iteration protocol
console.log(v);
}
1 2 3
PHP v8.6.0
// a function containing yield returns a Generator: produces one value then pauses, lazy execution
function countTo(int $n): Generator {
for ($i = 1; $i <= $n; $i++) {
yield $i;
}
}
foreach (countTo(3) as $v) { // the function body executes step by step during iteration
echo $v, "\n";
}
// produce on demand for large files/sequences, avoiding loading everything into memory at once
1 2 3
Python v3.15.2
def count_to(n):
for i in range(1, n + 1):
yield i # yield makes it a generator function: lazy production
g = count_to(3)
print(next(g)) # next() manually takes the next value: 1
print(next(g)) # 2
print(list(count_to(3))) # drain the generator in one shot
1 2 [1, 2, 3]
Rust v1.99.1
// Rust has no yield syntax: implement the Iterator trait (hand-written next),
// or compose iterator adapters (map/filter, etc., also lazy)
struct CountTo {
cur: i32,
max: i32,
}
impl Iterator for CountTo {
type Item = i32;
fn next(&mut self) -> Option<i32> {
if self.cur <= self.max {
let v = self.cur;
self.cur += 1;
Some(v)
} else {
None
}
}
}
fn main() {
for v in (CountTo { cur: 1, max: 3 }) {
println!("{}", v);
}
let doubled: Vec<i32> = (1..=3).map(|x| x * 2).collect(); // adapter composition
println!("{:?}", doubled);
}
1 2 3 [2, 4, 6]
TypeScript v26.13.1
function* countTo(n: number): Generator<number, void, unknown> {
for (let i = 1; i <= n; i++) {
yield i; // produces one value then pauses each time
}
}
for (const v of countTo(3)) {
console.log(v);
}
1 2 3
Language differences
C: no yield — a stateful iterator function hand-rolls a lazy generator (state held by the caller or a static variable).
C++: before C++20 coroutines (co_yield), the idiom is a hand-written generator class that keeps state and yields lazily (same semantics as PHP Generator).
Go: no yield — simulated with a goroutine plus channel (backpressure comes for free, at some scheduling cost).
Java: no yield syntax — Stream pipeline intermediate operations are lazy and run only when a terminal operation (forEach/collect) executes; the source can be a collection or functions like Stream.generate(Supplier) and Stream.iterate, but there is still no suspend/resume generator mechanism.
JavaScript: native yield — function* generator objects implementing the iteration protocol.
PHP: native yield — the function returns a Generator; all three (PHP/Python/JS) execute lazily, producing and consuming values on demand, which suits streaming large files.
Python: native yield — a function containing yield is a generator; next() pulls values manually.
Rust: no yield — hand-write Iterator::next or use iterator adapters (map/filter are likewise lazy and compute only on collect); core::iter::from_fn also works.