Control Flow
In Turbo, control flow constructs are expressions that return values.
If / Else Expressions
if is an expression -- it returns the value of whichever branch executes:
fn classify(n: i64) -> str {
if n > 0 { "positive" }
else { if n < 0 { "negative" } else { "zero" } }
}
fn main() {
let x = 10
let label = if x > 5 { "big" } else { "small" }
print(label) // big
}While Loops
fn main() {
let mut i = 0
while i < 5 {
print(i)
i += 1
}
}For-In Loops and Ranges
Iterate over arrays or ranges with for..in:
fn main() {
// Range: 0, 1, 2, 3, 4
for i in 0..5 {
print(i)
}
// Iterate over an array
let names = ["Alice", "Bob", "Charlie"]
for name in names {
print("Hello, {name}!")
}
}String loops in Edition 2027
Turbo 0.17.0 visits one Unicode scalar per iteration in native string loops. An empty string runs zero iterations. You can break as soon as you find the character you need.
function main(): void {
for (const ch of "A🍋B") {
if (ch === "B") { break; }
print(ch);
}
}Break and Continue
fn main() {
let mut i = 0
while i < 100 {
if i == 5 {
break // exit the loop
}
if i % 2 == 0 {
i += 1
continue // skip to next iteration
}
print(i)
i += 1
}
}Match Expressions
match is a powerful expression for pattern matching on values:
fn describe(n: i64) -> str {
match n {
0 => "zero"
1 => "one"
2 => "two"
_ => "many"
}
}
fn main() {
print(describe(0)) // zero
print(describe(1)) // one
print(describe(42)) // many
}Match Guards
Add conditions to match arms with if guards:
fn classify(n: i64) -> str {
match n {
0 => "zero"
n if n > 0 => "positive"
_ => "negative"
}
}
fn main() {
print(classify(5)) // positive
print(classify(0)) // zero
print(classify(-3)) // negative
}Pattern Matching on Enums
Match expressions destructure enum variants:
type Shape {
Circle(f64)
Rectangle(f64, f64)
}
fn area(s: Shape) -> str {
match s {
Circle(r) => "circle"
Rectangle(w, h) => "rectangle"
}
}
fn main() {
let s = Shape.Circle(5.0)
print(area(s)) // circle
}The compiler checks that match expressions are exhaustive -- if you miss a variant, you get a compile error (E0200).