6. Statements
| Statement | Meaning |
|---|---|
const / var declaration |
section 4 |
x = e, p.f = e, a[i] = e |
assign to a variable, a field or an element of a mutable variable |
if (c) { } else if (c) { } else { } |
c must be bool; braces are required |
while (c) { } |
repeats while c is true |
for (xs) \|x\| { }, for (xs) \|x, i\| { } |
each element of an array, a slice, a Buf or a str (bytes, as u8), with its index i |
break, continue |
leave or restart the innermost loop (E126 outside one) |
switch (x) { ... } |
section 10 |
return / return e |
section 5 |
defer e, errdefer e |
run e when the block is left; section 21 |
| expression | must have type void (E113); a result or an error may not be dropped silently |
_ = e |
evaluates e and drops its value: not void, not an error union (_ = try f()), and nothing owned, which would never be freed (E113) |
Loop variables are constants; name one _ to ignore it. Rule E113 is why
two() alone on a line is an error when two returns i64, and why a
!void call must be handled with try or catch.
// expect: 1
// expect: 3
uses io
fn main(io: Io) void {
const xs = [4]i64{ 1, 2, 3, 4 }
for (xs) |x, i| {
if (x % 2 == 0) {
continue
}
if (i > 2) {
break
}
io.print(x)
}
}