let x = 5
if x > 10 {
print("big")
} elif x > 0 {
print("small")
} else {
print("non-positive")
}
if/elif/else can be used as expressions. The last expression in each branch is the value:
let x = if cond { 1 } else { 2 }
let label = if val == 1 { "one" } elif val == 2 { "two" } else { "other" }
let result = if ready {
let a = compute()
a + 1
} else {
0
}
A shorter inline form is also available:
let label = "even" if x % 2 == 0 else "odd"
mut i = 0
while i < 5 {
print(i)
i += 1
}
for i in range(5) {
print(i)
}
for i in range(0, 10, 2) {
print(i)
}
let names = ["Alice", "Bob"]
for name in names {
print(name)
}
for (i, name) in enumerate(names) {
print(f"{i}: {name}")
}
break exits the innermost loop. continue skips to the next iteration.
Pattern matching works with literals, enums, tuples, and a wildcard _:
let x = 2
match x {
case 1 {
print("one")
}
case 2 | 3 {
print("two or three")
}
case n if n > 10 {
print(f"big: {n}")
}
case _ {
print("other")
}
}
Guards use if after the pattern. Or-patterns use |. See Enums and pattern matching for enum destructuring, tuple patterns, and Result patterns.