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
+40Lines changed: 40 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -117,6 +117,44 @@ loop {
117
117
}
118
118
```
119
119
120
+
## `const` blocks
121
+
122
+
> **<sup>Syntax</sup>**\
123
+
> _ConstBlockExpression_ :\
124
+
> `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
+
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
+
It also supports type inference so there is no need to specify the type, unlike [constant items].
130
+
131
+
Const blocks have 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.
133
+
For example, this code:
134
+
135
+
```rust
136
+
fnfoo<T>() ->usize {
137
+
const { std::mem::size_of::<T>() +1 }
138
+
}
139
+
```
140
+
141
+
is equivalent to:
142
+
143
+
```rust
144
+
fnfoo<T>() ->usize {
145
+
{
146
+
structConst<T>(T);
147
+
impl<T> Const<T> {
148
+
constCONST:usize=std::mem::size_of::<T>() +1;
149
+
}
150
+
Const::<T>::CONST
151
+
}
152
+
}
153
+
```
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.
0 commit comments