Suggest const block, instead of const item, for array repeat of non-Copy element #126894
Closed
Description
Code
struct Thing;
fn main() {
let _ = [Thing; 2];
}
Current output
error[E0277]: the trait bound `Thing: Copy` is not satisfied
--> src/main.rs:4:14
|
4 | let _ = [Thing; 2];
| ^^^^^ the trait `Copy` is not implemented for `Thing`
|
= note: the `Copy` trait is required because this value will be copied for each element of the array
= help: create an inline `const` block, see RFC #2920 <https://github.com/rust-lang/rfcs/pull/2920> for more information
help: consider annotating `Thing` with `#[derive(Copy)]`
|
1 + #[derive(Copy)]
2 | struct Thing;
|
help: consider creating a new `const` item and initializing it with the result of the constructor to be used in the repeat position
|
4 ~ const ARRAY_REPEAT_VALUE: Thing = Thing;
5 ~ let _ = [ARRAY_REPEAT_VALUE; 2];
|
Rationale and extra context
Rustc's suggestion to make this code compile with a non-Copy type is:
fn main() {
const ARRAY_REPEAT_VALUE: Thing = Thing;
let _ = [ARRAY_REPEAT_VALUE; 2];
}
Instead it should be:
fn main() {
let _ = [const { Thing }; 2];
}
Relatedly, now that const blocks are a stable part of the language since Rust 1.79 (https://blog.rust-lang.org/2024/06/13/Rust-1.79.0.html#inline-const-expressions), I don't think the diagnostic should be linking to the initial const block RFC.
Rust Version
rustc 1.81.0-nightly (bcf94dec5 2024-06-23)
binary: rustc
commit-hash: bcf94dec5ba6838e435902120c0384c360126a26
commit-date: 2024-06-23
host: x86_64-unknown-linux-gnu
release: 1.81.0-nightly
LLVM version: 18.1.7