Skip to content

Suggest creating a const when calling a const function in an array initializer #73734

Closed
@Aaron1011

Description

@Aaron1011

The following code:

fn main() {
    let strs: [String; 5] = [String::new(); 5];
}

gives the following error:

error[E0277]: the trait bound `std::string::String: std::marker::Copy` is not satisfied
 --> src/main.rs:2:29
  |
2 |     let strs: [String; 5] = [String::new(); 5];
  |                             ^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::string::String`
  |
  = note: the `Copy` trait is required because the repeated element will be copied

However, String::new() is a const fn, so this code can be made to compile by creating a new const item:

fn main() {
    const EMPTY: String = String::new();
    let strs: [String; 5] = [EMPTY; 5];
}

We should suggest this to user when a const function is being called in the array initializer.

Assuming that rust-lang/rfcs#2920 is accepted, we could eventually suggest an inline const block.
On Nightly, we could suggest an inline const block.

Metadata

Metadata

Labels

A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions