Skip to content

Control Flow

if is an expression — it produces a value:

let max = if a > b { a } else { b }

Multi-branch:

if score >= 90 {
print("A")
} else if score >= 80 {
print("B")
} else if score >= 70 {
print("C")
} else {
print("F")
}

Iterate over collections:

for item in [1, 2, 3] {
print(item)
}

With index:

for (i, item) in list.enumerate() {
print("{i}: {item}")
}

Range-based:

for i in 0..10 {
print(i) // 0 through 9
}
for i in 0..=10 {
print(i) // 0 through 10 (inclusive)
}
let mut count = 0
while count < 10 {
print(count)
count = count + 1
}
loop {
let input = read_line()
if input == "quit" {
break
}
print("You said: " + input)
}
for i in 0..100 {
if i % 2 == 0 {
continue // skip even numbers
}
if i > 10 {
break // stop after 10
}
print(i)
}

Pattern matching is one of Zap’s most powerful features:

match value {
0 => print("zero"),
1 | 2 | 3 => print("small"),
n if n < 0 => print("negative"),
_ => print("other"),
}
match shape {
Shape.Circle(r) => 3.14159 * r * r,
Shape.Rectangle(w, h) => w * h,
Shape.Triangle(a, b, c) => {
let s = (a + b + c) / 2.0
sqrt(s * (s - a) * (s - b) * (s - c))
},
}
match find_user(id) {
Some(user) => print("Found: " + user.name),
None => print("User not found"),
}

Learn about the module system to organise larger programs.