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
+20-3
Original file line number
Diff line number
Diff line change
@@ -129,7 +129,7 @@ Const blocks allows you to define a constant value without having to define new
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 is on a program path that gets executed at runtime, then the const block 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
169
+
iffalse {
170
+
// The panic may or may not occur when the program is built.
0 commit comments