Statements
A function body is a block: a sequence of statements between { and }, run in order. Every statement is one of these:
| Statement | Form | Page |
|---|---|---|
| Binding | let x = …; var x = …; | Bindings |
| Constant | const X = …; | Constants |
| Expression | expression; | below |
if | if c { … } else { … } | if |
when | when c { … } | Conditional compilation |
match | match v { … } | match |
while, do while, loop, for | while c { … } … | Loops |
break, continue | break; continue label; | break and continue |
return | return value; | return |
fail | fail error; | Errors |
defer | defer statement | defer |
Expression statements
An expression followed by ; is a statement, run for its effect: a call, an assignment, an increment.
PrintLine("hello");
total += price;
count++;
The ; is required. When something else follows a complete expression, the compiler names it: error: expected ';' after expression, but found ':'.
A call to a fallible function cannot be a bare statement, because its failure would be lost; handle it with ?, catch or match. A match at the start of a statement is a match statement; to use a match's value there, bind it or wrap it in parentheses.
Blocks are bodies
Braces appear only as the body of something — a function, an if branch, a loop, a match arm. A block on its own is not a statement:
let x = 1;
{
let y = 2;
}
error: expected an expression before '{'
A body is always a block, even when it holds one statement: if ready return 1; is error: expected '{' to start the 'if' body before 'return'. A value that needs a few statements to compute belongs in a function, or in a match arm.
Conditions
if, while, do while and the conditional operator test a condition, and every condition follows the same rules.
It is a bool. A number, a pointer or an optional is never true or false by itself:
let count: int32 = 3;
if count {
}
error: condition for 'if' must have type 'bool', but found 'int32'
Write the test: if count != 0.
It needs no parentheses. if count > 0 { … } is the usual form. Parentheses are allowed, as around any expression, but add nothing: if (count > 0) { … } means the same.
A structure literal inside it is parenthesised. After if, while, for … in, match and when, the first { that could start the body does start the body. So Point { x: 1, y: 2 } cannot appear bare in a condition — its brace would be taken as the body:
if p == (Point { x: 1, y: 2 }) {
PrintLine("at the start");
}
Without the parentheses the compiler reports error: expected ';' after expression, but found ':' at the first field. A structure literal inside a call's argument list needs no extra parentheses, since the call's own parentheses already enclose it.
See also
- if, Loops, break and continue, return
- match — choosing by the shape of a value
- Expressions — what statements are built from
- Learn: Control flow