05 · Control Flow
Handle an empty iteration
The else block after for runs only when no item enters the body. With for case, unmatched items do not count. A break after a successful iteration does not run else; the loop binding is unavailable in the else block.
On this page
The else block after for runs only when no item enters the body. With for case, unmatched items do not count. A break after a successful iteration does not run else; the loop binding is unavailable in the else block.
Complete example
Handle an empty iteration.
empty_iteration.zolo
// Show an empty search result without a second count or duplicate traversal.
struct Product { name: str, stock: int }
let products = [Product { name: "Keyboard", stock: 3 }, Product { name: "Mouse", stock: 0 }]
let available = [for product in products => if product.stock > 0 => product]
for product in available {
print("Available: {product.name}")
} else {
print("No products available")
}
let empty: [Product] = []
for product in empty { print(product.name) } else { print("No search results") }
enum Reply { Found(str), Missing }
let replies = [Reply.Missing, Reply.Missing]
for case .Found(name) in replies {
print(name)
} else {
print("No matching replies")
}
Reference
zolo run examples/features/empty_iteration.zolo --no-cache
See also