Skip to content

Commit f9d9aa4

Browse files
committed
Add const blocks
1 parent 9f0cc13 commit f9d9aa4

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/expressions.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
>       | [_FieldExpression_]\
2424
>       | [_ClosureExpression_]\
2525
>       | [_AsyncBlockExpression_]\
26+
>       | [_ConstBlockExpression_]\
2627
>       | [_ContinueExpression_]\
2728
>       | [_BreakExpression_]\
2829
>       | [_RangeExpression_]\
@@ -311,6 +312,7 @@ They are never allowed before:
311312
[_ClosureExpression_]: expressions/closure-expr.md
312313
[_ComparisonExpression_]: expressions/operator-expr.md#comparison-operators
313314
[_CompoundAssignmentExpression_]: expressions/operator-expr.md#compound-assignment-expressions
315+
[_ConstBlockExpression_]: expressions/block-expr.md#const-blocks
314316
[_ContinueExpression_]: expressions/loop-expr.md#continue-expressions
315317
[_FieldExpression_]: expressions/field-expr.md
316318
[_GroupedExpression_]: expressions/grouped-expr.md

src/expressions/block-expr.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,37 @@ loop {
117117
}
118118
```
119119
120+
## `const` blocks
121+
122+
> **<sup>Syntax</sup>**\
123+
> _ConstBlockExpression_ :\
124+
> &nbsp;&nbsp; `const` _BlockExpression_
125+
126+
A *const block* is a variant of a block expression which evaluates in the compile time instead of in the run time.
127+
128+
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`.
129+
130+
For example, this code:
131+
132+
```rust
133+
# fn foo(x: i32) -> i32 { x }
134+
fn main() {
135+
let x = foo(const { 1 + 1 });
136+
}
137+
```
138+
139+
is equivalent to:
140+
141+
```rust
142+
# fn foo(x: i32) -> i32 { x }
143+
fn main() {
144+
const FOO: i32 = 1 + 1;
145+
let x = foo(FOO);
146+
}
147+
```
148+
149+
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.
150+
120151
## `unsafe` blocks
121152

122153
> **<sup>Syntax</sup>**\

0 commit comments

Comments
 (0)