Skip to content

Commit 4c96c01

Browse files
committed
Add a section for const value repetition
1 parent 33a353f commit 4c96c01

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

posts/2021-02-11-Rust-1.50.0.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,36 @@ fn main() {
5252
}
5353
```
5454

55+
### `const` value repetition for arrays
56+
57+
Arrays in Rust can be written either as a list `[a, b, c]` or a repetition `[x; N]`.
58+
For lengths `N` greater than one, repetition has only been allowed for `Copy`
59+
types, and [RFC 2203] sought to allow any `const` expression there. However,
60+
while that feature was unstable for arbitrary expressions, its implementation
61+
since Rust 1.38 accidentally allowed stable use of `const` _values_ in array
62+
repetition.
63+
64+
```rust
65+
fn main() {
66+
// This is not allowed, because `Option<Vec<i32>>` does not implement `Copy`.
67+
let array: [Option<Vec<i32>>; 10] = [None; 10];
68+
69+
const NONE: Option<Vec<i32>> = None;
70+
const EMPTY: Option<Vec<i32>> = Some(Vec::new());
71+
72+
// However, repeating a `const` value is allowed!
73+
let nones = [NONE; 10];
74+
let empties = [EMPTY; 10];
75+
}
76+
```
77+
78+
In Rust 1.50, that stabilization is formally acknowledged, so you may use this
79+
construct without fear. In the future, to avoid such "temporary" named
80+
constants, you can look forward to inline `const` expressions per [RFC 2920].
81+
82+
[RFC 2203]: https://rust-lang.github.io/rfcs/2203-const-repeat-expr.html
83+
[RFC 2920]: https://rust-lang.github.io/rfcs/2920-inline-const.html
84+
5585
### Safe assignments to `ManuallyDrop<T>` union fields
5686

5787
Rust 1.49 made it possible to add `ManuallyDrop<T>` fields to a `union` as part

0 commit comments

Comments
 (0)