Skip to content

Control flow

A block is a sequence of expressions inside braces. The last expression is the block’s value. Bindings inside a block are not visible outside of it.

let value = {
let a = 1
let b = 2
a + bvalue is 3
}

if runs a block when a condition is true.

if attempts >= 3 {
locked = true
}

An optional else runs a block when the condition is false.

if balance >= price {
balance -= price
} else {
declined += 1
}

An if with an else produces the value of the branch that runs. Every branch must produce the same type.

let result = if get_score() >= 80 { "pass" } else { "fail" }
stringstringstring

Runs the body when a pattern matches. Typically used with Option.

let mut ages = Map.new<string, int>()
ages["Alice"] = 30
if let Some(age) = ages.get("Alice") {
fmt.Println(f"Alice is {age}")
}

With an else, if let returns the value of the branch that runs:

let message = if let Some(age) = ages.get("Bob") {
f"Bob is {age}"
} else {
"Bob's age is unknown"
}

Iterates over a collection or range.

read-only copy of each element
for item in items {
fmt.Println(item)
}
mutable copy of each element
for mut item in items {
item *= 2
fmt.Println(item)
}

Writing to a mutable copy does not affect the original. To write to the original in the collection, write through the index.

for mut item in items {
item *= 2does not change items
fmt.Println(item)
}
for i in 0..items.length() {
items[i] *= 2changes items
}

for mut makes a Slice, Map, or Ref element writable, so a write through it changes the original.

let mut rows = [[1, 2], [3, 4]]
mut Slice<int>
for mut row in rows {
row[0] = 99changes rows
}

Supported iterables:

IterableElement type
Slice<T>T
Array<T, N>T
Map<K, V>(K, V)
Range<T>, RangeInclusive<T>, RangeFrom<T>T
Channel<T>, Receiver<T>T
EnumeratedSlice<T>(int, T)
iter.Seq<T>T
iter.Seq2<K, V>(K, V)

A loop over a Map must bind each entry as a (key, value) pair:

for (name, age) in ages {
fmt.Println(name, age)
}

enumerate() pairs each element of a Slice with its index:

for (i, item) in items.enumerate() {
fmt.Println(i, item)
}

Repeats while a condition is true.

let mut total = 0
while total < 10 {
total += 3
}

Repeats as many times as a pattern matches.

let mut i = 0
while let Some(item) = items.get(i) {
fmt.Println(item)
i += 1
}

Loops forever. Exit with break.

let mut n = 0
loop {
n += 1
if n == 10 {
break
}
}

break can carry a value, which becomes the value of the loop.

let mut n = 0
let result = loop {
n += 7
if n > 20 {
break nresult is 21
}
}

A bare break gives the loop type ().

break exits a loop. continue skips to the next iteration of the loop.

for i in 0..100 {
if i % 2 == 0 {
continue
}
if i > 50 {
break
}
fmt.Println(i)
}

There are no labeled breaks. break and continue always apply to the innermost loop.

Returns early from the current function. A bare return returns ().

fn find(items: Slice<int>, target: int) -> Option<int> {
for i in 0..items.length() {
if items[i] == target {
return Some(i)early return
}
}
None
}

Schedules an expression to run whenever the enclosing function returns.

fn file_size(path: string) -> Result<int64, error> {
let file = os.Open(path)?
defer file.Close()runs whether file.Stat() succeeds or fails
let info = file.Stat()?
Ok(info.Size())
}

When a function has several defer calls, the last one scheduled runs first.

defer fmt.Println("first")
defer fmt.Println("second")runs before first

A defer block groups cleanup steps that belong together. Inside one block the steps run in the order written, top to bottom.

defer {
conn.flush()runs first
conn.close()runs second
}