Skip to content

Constants in array repeat expression feature doesn't work with unit structs #80890

Closed
@rodrimati1992

Description

@rodrimati1992

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions