You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: src/expressions/block-expr.md
+21-4
Original file line number
Diff line number
Diff line change
@@ -123,13 +123,13 @@ loop {
123
123
> _ConstBlockExpression_ :\
124
124
> `const`_BlockExpression_
125
125
126
-
A *const block* is a variant of a block expression which evaluates at compile-time instead of at runtime.
126
+
A *const block* is a variant of a block expression whose body evaluates at compile-time instead of at runtime.
127
127
128
128
Const blocks allows you to define a constant value without having to define new [constant items], and thus they are also sometimes referred as *inline consts*.
129
129
It also supports type inference so there is no need to specify the type, unlike [constant items].
130
130
131
131
Const blocks have the ability to reference generic parameters in scope, unlike [free][free item] constant items.
132
-
They are desugared to associated constant items with generic parameters in scope.
132
+
They are desugared to constant items with generic parameters in scope (similar to associated constants, but without a trait or type they are associated with).
133
133
For example, this code:
134
134
135
135
```rust
@@ -152,8 +152,25 @@ fn foo<T>() -> usize {
152
152
}
153
153
```
154
154
155
-
This also means that const blocks are treated similarly to associated constants.
156
-
For example, they are not guaranteed to be evaluated when the enclosing function is unused.
155
+
If the const block expression is executed at runtime, then the constant is guaranteed to be evaluated, even if its return value is ignored:
156
+
157
+
```rust
158
+
fnfoo<T>() ->usize {
159
+
// If this code ever gets executed, then the assertion has definitely
160
+
// been evaluated at compile-time.
161
+
const { assert!(std::mem::size_of::<T>() > 0); }
162
+
// Here we can have unsafe code relying on the type being non-zero-sized.
163
+
/* ... */
164
+
}
165
+
```
166
+
167
+
If the const block expression is not executed at runtime, it may or may not be evaluated:
168
+
```rust,compile_fail
169
+
if false {
170
+
// The panic may or may not occur when the program is built.
0 commit comments