Go 1.23: Range Over Func Iterators & Deferred Function Panics
Explore Go 1.23's game-changing range-over-func feature, improved error handling in deferred functions, and practical examples for modern concurrent systems.
Go 1.23: A Milestone for Iterators and Concurrency Control
Go 1.23, released in August 2024, introduces a powerful new language feature that fundamentally changes how developers write loops and work with iterators: range-over-func. Combined with improved panic handling in deferred functions and several performance enhancements, this release marks a significant step forward for Go’s ecosystem. Whether you’re building microservices, data processing pipelines, or high-concurrency systems, these features will make your code cleaner, safer, and more performant.
In this deep-dive, we’ll explore the mechanics of range-over-func, understand how it simplifies iterator patterns, and show you how it integrates with Go’s concurrency model.
Understanding Range Over Func: Beyond Slices and Maps
Since Go’s inception, the range keyword has been limited to built-in types: arrays, slices, strings, maps, and channels. For custom data structures or lazy-evaluated sequences, developers had to resort to either:
- Channel-based iteration — spawning goroutines and feeding data through channels
- Callback patterns — passing functions and manually managing state
- Custom iterator types — implementing complex state machines
Go 1.23 changes this with range-over-func, a language feature that allows you to define custom iteration behavior for any type.
The Core Concept
Range-over-func works by allowing a type to define an iterator method that accepts a yield function. The iterator is responsible for calling yield for each element, and can stop early if yield returns false.
// Before Go 1.23 — manual callback pattern
func processUserIDs(fn func(int) error) error {
for id := 1; id <= 1000; id++ {
if err := fn(id); err != nil {
return err
}
}
return nil
}
func main() {
err := processUserIDs(func(id int) error {
fmt.Printf("Processing user %d\n", id)
if id == 42 {
return fmt.Errorf("user 42 blocked")
}
return nil
})
if err != nil {
log.Fatal(err)
}
}
With Go 1.23, this becomes far more natural:
// Go 1.23 — range-over-func pattern
func (u *UserDB) All(yield func(int) bool) {
for id := 1; id <= 1000; id++ {
if !yield(id) {
return // caller broke out of range loop
}
}
}
func main() {
db := &UserDB{}
for id := range db.All {
fmt.Printf("Processing user %d\n", id)
if id == 42 {
break // gracefully exits iterator
}
}
}
Two-Value Iteration
For complex data structures, you can also yield key-value pairs:
type OrderLog struct {
orders map[int]string // orderID -> status
}
// Define a range-over-func iterator
func (ol *OrderLog) All(yield func(int, string) bool) {
for orderID, status := range ol.orders {
if !yield(orderID, status) {
return
}
}
}
func main() {
log := &OrderLog{
orders: map[int]string{
1: "pending",
2: "shipped",
3: "delivered",
},
}
// Range over key-value pairs naturally
for orderID, status := range log.All {
fmt.Printf("Order %d: %s\n", orderID, status)
}
}
This is cleaner than callback chains and doesn’t require goroutines, making it ideal for CPU-bound operations.
Practical Use Case: Lazy Evaluation and Chaining
One of the most powerful applications of range-over-func is building lazy, composable iterator chains. Consider a data processing pipeline:
type DataStream struct {
data []int
}
// All yields all items
func (ds *DataStream) All(yield func(int) bool) {
for _, v := range ds.data {
if !yield(v) {
return
}
}
}
// Filter creates a filtered view
func (ds *DataStream) Filter(predicate func(int) bool) func(func(int) bool) {
return func(yield func(int) bool) {
for v := range ds.All {
if predicate(v) {
if !yield(v) {
return
}
}
}
}
}
// Map transforms values
func (ds *DataStream) Map(transform func(int) int) func(func(int) bool) {
return func(yield func(int) bool) {
for v := range ds.All {
if !yield(transform(v)) {
return
}
}
}
}
func main() {
stream := &DataStream{
data: []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
}
// Chain operations: filter even numbers, then double them
for v := range stream.Filter(func(x int) bool {
return x%2 == 0
}).Map(func(x int) int {
return x * 2
}) {
fmt.Printf("Result: %d\n", v) // Output: 4, 8, 12, 16, 20
}
}
This pattern is memory-efficient because values are computed on-demand, not materialized into intermediate slices.
Improved Panic Handling in Deferred Functions
Go 1.23 also enhances how panics are handled within deferred functions. The language now better distinguishes between panics that occur in the deferred function itself versus panics that propagate from the surrounding code.
The Problem
In earlier Go versions, if a deferred function panicked while handling a previous panic, the behavior was unclear:
func problematicDefer() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered: %v\n", r)
panic("new panic in defer") // This overwrites the original panic
}
}()
panic("original panic")
}
In Go 1.22 and earlier, the original panic would be lost. Go 1.23 improves this by using panic chains, allowing you to track multiple panics:
func main() {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
fmt.Printf("Error chain: %+v\n", err)
}
}
}()
defer func() {
if r := recover(); r != nil {
panic(fmt.Errorf("deferred function panicked while handling %v", r))
}
}()
panic("original error")
}
With Go 1.23’s panic chains, you can now inspect both the original and derivative panics, making debugging multi-layered failures much easier.
Performance Improvements and Optimizations
Go 1.23 includes several under-the-hood optimizations:
1. Improved Inlining
The compiler is more aggressive about inlining small range-over-func iterators, reducing function call overhead.
2. Better Escape Analysis
Variables are more accurately analyzed for heap allocation, reducing garbage collection pressure in tight loops.
3. Loop Unrolling
The compiler can now unroll simple iterator loops when it’s safe to do so, yielding 5-10% improvements in throughput for data-heavy workloads.
Getting Started with Go 1.23
Installation
Download and install Go 1.23 from golang.org:
# macOS
brew upgrade go
# Or download the binary
wget https://go.dev/dl/go1.23.linux-amd64.tar.gz
tar -C /usr/local -xzf go1.23.linux-amd64.tar.gz
Verify installation:
go version
# go version go1.23 linux/amd64
Updating Your Project
Update your go.mod file:
go 1.23
Then run:
go mod tidy
go test ./...
Step-by-Step Guide: Building a Custom Iterator
Let’s build a practical iterator for a file-based log reader:
Step 1: Define Your Type
type LogFile struct {
path string
}
type LogEntry struct {
timestamp time.Time
level string
message string
}
Step 2: Implement the Iterator
import (
"bufio"
"os"
"strings"
"time"
)
func (lf *LogFile) Lines(yield func(LogEntry) bool) error {
file, err := os.Open(lf.path)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
entry, err := parseLine(line)
if err != nil {
continue // skip malformed lines
}
if !yield(entry) {
break // caller broke out of loop
}
}
return scanner.Err()
}
func parseLine(line string) (LogEntry, error) {
// Simple parser
parts := strings.SplitN(line, " ", 3)
if len(parts) < 3 {
return LogEntry{}, fmt.Errorf("invalid format")
}
ts, _ := time.Parse(time.RFC3339, parts[0])
return LogEntry{
timestamp: ts,
level: parts[1],
message: parts[2],
}, nil
}
Step 3: Use the Iterator
func main() {
log := &LogFile{path: "/var/log/app.log"}
err := log.Lines(func(entry LogEntry) bool {
if entry.level == "ERROR" {
fmt.Printf("[%s] %s\n", entry.timestamp, entry.message)
}
return true // continue iteration
})
if err != nil {
log.Fatal(err)
}
}
// Or use it in a range loop
log.Lines(func(entry LogEntry) bool {
fmt.Printf("%s: %s\n", entry.level, entry.message)
return true
})
}
Notice how we can use a single iterator with different callbacks — no need for separate methods for filtering, mapping, or early termination.
Common Pitfalls and Best Practices
Pitfall 1: Forgetting to Check the Yield Return Value
If the caller breaks out of a range loop, your iterator might continue working needlessly:
// ❌ Bad: ignoring yield return value
func (ds *DataStream) All(yield func(int) bool) {
for _, v := range ds.data {
yield(v) // Not checking if caller broke out
}
}
// ✅ Good: respect the break
func (ds *DataStream) All(yield func(int) bool) {
for _, v := range ds.data {
if !yield(v) {
return
}
}
}
Pitfall 2: Panicking Instead of Returning Errors
Range-over-func iterators should propagate errors through return values, not panics:
// ❌ Bad: panic on error
func (db *Database) Rows(yield func(Row) bool) {
rows, err := db.query()
if err != nil {
panic(err) // Breaks caller's loop abruptly
}
// ...
}
// ✅ Good: return error separately
func (db *Database) Rows(yield func(Row) bool) error {
rows, err := db.query()
if err != nil {
return err
}
// ...
}
Pitfall 3: Sharing Mutable State Across Yields
If you reuse a single value struct across multiple yields, the caller may accidentally modify it:
// ❌ Bad: reusing the same pointer
func (ds *DataStream) Items(yield func(*Item) bool) {
item := &Item{}
for _, v := range ds.data {
item.ID = v
if !yield(item) { // Caller gets same pointer each time
return
}
}
}
// ✅ Good: create new value for each yield
func (ds *DataStream) Items(yield func(Item) bool) {
for _, v := range ds.data {
item := Item{ID: v}
if !yield(item) { // Fresh copy each iteration
return
}
}
}
Why It Matters: Real-World Impact
Range-over-func addresses a long-standing pain point in Go: custom iteration patterns. Consider a typical data pipeline:
Before Go 1.23:
- Required goroutines and channels for lazy evaluation
- Heavy memory overhead (buffered channels, goroutine stack space)
- Harder to compose multiple operations
- Difficult to handle errors mid-iteration
With Go 1.23:
- Lightweight, synchronous iterators
- Minimal memory footprint
- Natural composition with range syntax
- Error handling via function returns
For high-performance systems processing millions of records, this translates to:
- 5-20% reduction in memory usage for typical pipelines
- 10-30% faster throughput due to reduced GC pressure
- Cleaner, more maintainable code
Integrating with CI/CD and Testing
When updating to Go 1.23, leverage tools to validate your code quality. You can use the API Request Builder to test HTTP endpoints that your Go services expose, or the Mock Data Generator to create test fixtures for your iterators.
For testing iterators themselves, here’s a pattern:
func TestLogFileIterator(t *testing.T) {
log := &LogFile{path: "test.log"}
var entries []LogEntry
err := log.Lines(func(entry LogEntry) bool {
entries = append(entries, entry)
return true
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(entries) != 3 {
t.Errorf("expected 3 entries, got %d", len(entries))
}
}
Performance Benchmarking
To validate that your iterators are performant, run benchmarks:
func BenchmarkLogFileIteration(b *testing.B) {
log := &LogFile{path: "large.log"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
count := 0
log.Lines(func(entry LogEntry) bool {
count++
return true
})
}
}
Run with:
go test -bench=. -benchmem
# BenchmarkLogFileIteration-8 1000 1234567 ns/op 8192 B/op 12 allocs/op
Conclusion
Go 1.23 marks a turning point for Go’s approach to iteration and control flow. The range-over-func feature brings the expressiveness of modern functional languages to Go while maintaining its simplicity and performance characteristics. Combined with improved error handling in deferred functions and optimizations under the hood, Go 1.23 equips developers with powerful tools for building concurrent, data-intensive systems.
Start experimenting with range-over-func in your projects today. You’ll likely find opportunities to simplify iterators, reduce memory overhead, and write more idiomatic Go code. For testing your APIs and validating data transformations, consider using Kloubot’s Mock Data Generator to create realistic test datasets.
The future of Go iteration is here — and it’s elegant.