Skip to content

Proposal: Range Over Function Types #2607

@xushiwei

Description

@xushiwei

This proposal adds support for ranging over function values in XGo, aligning with Go 1.23's iterator functions feature. This enables developers to create custom iterators with clean, idiomatic syntax.

Background

Go 1.23 introduced the ability to use range with function types, allowing functions to act as iterators. This powerful feature enables:

  • Custom iteration patterns
  • Lazy evaluation
  • Resource management through iteration
  • Cleaner APIs for sequential data

XGo should support this feature to maintain compatibility and provide modern iteration capabilities.

Proposal

Allow range to work with function types that match specific signatures:

func(yield func() bool)                    // 0 values
func(yield func(V) bool)                   // 1 value
func(yield func(K, V) bool)                // 2 values (key-value pairs)

The yield function is called by the iterator to produce values. It returns bool indicating whether iteration should continue (true) or stop (false, e.g., when break is encountered).

Examples

func foo(yield func() bool) {
	yield()
}

func bar(yield func(v string) bool) {
	yield("World")
}

func weekdays(yield func(k string, v int) bool) {
	yield("Mon", 1)
	yield("Tue", 2)
	yield("Wed", 3)
}

// Zero-value iterator
for range foo {
    println("Hi")
}

// Single-value iterator
for v := range bar {
    println(v)  // Output: World
}

// Key-value iterator
for k, v := range weekdays {
    println(k, v)  // Output: Mon 1, Tue 2, Wed 3
}

Use Cases

  1. Custom collections: Iterate over tree structures, graphs, or custom data structures
  2. Generators: Produce infinite or computed sequences lazily
  3. Resource iteration: Files, database rows, network streams with automatic cleanup
  4. Functional patterns: Map, filter, reduce operations with iterator chains

Implementation

The compiler should:

  1. Recognize function types matching iterator signatures in range expressions
  2. Generate code to call the iterator function with an appropriate yield callback
  3. Handle break and continue by controlling the bool return value from yield
  4. Support early termination when yield returns false

Compatibility

This feature is backward compatible - existing code continues to work unchanged. Only code explicitly using range with function values is affected.

Conclusion

Range over function types modernizes XGo's iteration capabilities, enabling cleaner APIs and more expressive code while maintaining Go compatibility.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions