Skip to content

Commit

Permalink
Add const blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
nbdd0121 committed Nov 7, 2022
1 parent 9f0cc13 commit f9d9aa4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
>       | [_FieldExpression_]\
>       | [_ClosureExpression_]\
>       | [_AsyncBlockExpression_]\
>       | [_ConstBlockExpression_]\
>       | [_ContinueExpression_]\
>       | [_BreakExpression_]\
>       | [_RangeExpression_]\
Expand Down Expand Up @@ -311,6 +312,7 @@ They are never allowed before:
[_ClosureExpression_]: expressions/closure-expr.md
[_ComparisonExpression_]: expressions/operator-expr.md#comparison-operators
[_CompoundAssignmentExpression_]: expressions/operator-expr.md#compound-assignment-expressions
[_ConstBlockExpression_]: expressions/block-expr.md#const-blocks
[_ContinueExpression_]: expressions/loop-expr.md#continue-expressions
[_FieldExpression_]: expressions/field-expr.md
[_GroupedExpression_]: expressions/grouped-expr.md
Expand Down
31 changes: 31 additions & 0 deletions src/expressions/block-expr.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,37 @@ loop {
}
```
## `const` blocks

> **<sup>Syntax</sup>**\
> _ConstBlockExpression_ :\
> &nbsp;&nbsp; `const` _BlockExpression_
A *const block* is a variant of a block expression which evaluates in the compile time instead of in the run time.

A `const` block allows you to define a constant value without having to define a new `const` item, and thus is also sometimes called as inline `const` or anonymous `const`.

For example, this code:

```rust
# fn foo(x: i32) -> i32 { x }
fn main() {
let x = foo(const { 1 + 1 });
}
```

is equivalent to:

```rust
# fn foo(x: i32) -> i32 { x }
fn main() {
const FOO: i32 = 1 + 1;
let x = foo(FOO);
}
```

A `const` block supports type inference so you do not have to write the type of the constant value like a `const` item. `const` blocks are allowed to reference general parameters in their scope.

## `unsafe` blocks

> **<sup>Syntax</sup>**\
Expand Down

0 comments on commit f9d9aa4

Please sign in to comment.