Format for Expressions
This lesson discusses how to write any expression.
Blocks
- A block expression should have a newline after the initial
{
and before the terminal}
.
fn block_as_expr() {
let foo = {
a_call_inside_a_block();
// a comment in a block
the_value
};
}
- If a block has an attribute, it should be on its own line:
fn block_as_stmt() {
#[an_attribute]
{
#![an_inner_attribute]
// a comment in a block
the_value
}
}
-
Avoid writing comments on the same line as the braces.
-
An empty block should be written as {}.
-
A block may be written on a single line if:
- it is either used in expression position (not statement position) or is an unsafe block in statement position
- contains a single-line expression and no statements
- contains no comments
-
A single line block should have spaces after the opening brace and before the closing brace.
fn main() {
// Single line
let _ = { a_call() };
let _ = unsafe { a_call() };
// Not allowed on one line
// Statement position.
{
a_call()
}
// Contains a statement
let _ = {
a_call();
};
unsafe {
a_call();
}
// Contains a comment
let _ = {
// A comment
};
let _ = {
// A comment
a_call()
};
// Multiple lines
let _ = {
a_call();
another_call()
};
let _ = {
a_call(
an_argument,
another_arg,
)
};
}
The above information serves for writing most of the expressions in Rust. More information on Expressions can be found here.