Control flow
Blocks
Section titled “Blocks”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 else
Section titled “if else”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" }stringstringstringif let
Section titled “if let”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 elementfor item in items { fmt.Println(item)}mutable copy of each elementfor 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:
| Iterable | Element 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 = 0while total < 10 { total += 3}while let
Section titled “while let”Repeats as many times as a pattern matches.
let mut i = 0while let Some(item) = items.get(i) { fmt.Println(item) i += 1}Loops forever. Exit with break.
let mut n = 0loop { n += 1 if n == 10 { break }}break can carry a value, which becomes the value of the loop.
let mut n = 0let result = loop { n += 7 if n > 20 { break nresult is 21 }}A bare break gives the loop type ().
break and continue
Section titled “break and continue”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.
return
Section titled “return”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 firstA 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}