From f9d9aa4e8322afb75f25831fa06ca57645c4f0a0 Mon Sep 17 00:00:00 2001 From: Gary Guo Date: Mon, 7 Nov 2022 04:53:59 +0000 Subject: [PATCH] Add const blocks --- src/expressions.md | 2 ++ src/expressions/block-expr.md | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/expressions.md b/src/expressions.md index b2411cd8e..8529d5364 100644 --- a/src/expressions.md +++ b/src/expressions.md @@ -23,6 +23,7 @@ >       | [_FieldExpression_]\ >       | [_ClosureExpression_]\ >       | [_AsyncBlockExpression_]\ +>       | [_ConstBlockExpression_]\ >       | [_ContinueExpression_]\ >       | [_BreakExpression_]\ >       | [_RangeExpression_]\ @@ -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 diff --git a/src/expressions/block-expr.md b/src/expressions/block-expr.md index bd9c0a623..eeb76990f 100644 --- a/src/expressions/block-expr.md +++ b/src/expressions/block-expr.md @@ -117,6 +117,37 @@ loop { } ``` +## `const` blocks + +> **Syntax**\ +> _ConstBlockExpression_ :\ +>    `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 > **Syntax**\