Closed
Description
I tried this code:
#[derive(Debug)]
struct Foo;
fn main(){
let repeated = [Foo; 4];
println!("{:?}", repeated);
}
I expected to the code to compile without errors, since Foo
is a constant and constants in array repeat expression is stable
Instead, this happened: the code doesn't compile, saying that Foo
isn't Copy
error[E0277]: the trait bound `Foo: Copy` is not satisfied
--> src/main.rs:5:20
|
5 | let repeated = [Foo; 4];
| ^^^^^^^^ the trait `Copy` is not implemented for `Foo`
|
Unit structs are described as creating a constant of the same name in the reference:
https://doc.rust-lang.org/nightly/reference/items/structs.html
A unit-like struct is a struct without any fields, defined by leaving off the list of fields entirely. Such a struct implicitly defines a constant of its type with the same name.
Meta
rustc --version --verbose
:
1.51.0-nightly (2021-01-09 6184f23950fb4aa14884)
Workarounds
Defining the Foo
constant explicitly does compile:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=675dd9fdcc63bde83dfb33a5f0e19054
#[derive(Debug)]
struct Foo{}
const Foo: Foo = Foo{};
fn main(){
let repeated = [Foo; 4];
println!("{:?}", repeated);
}