Closed
Description
Code
fn main() {
let x = [None::<String>(); 10];
}
Current output
error[E0277]: the trait bound `String: Copy` is not satisfied
--> src/main.rs:2:14
|
2 | let x = [None::<String>; 10];
| ^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
|
= note: required for `Option<String>` to implement `Copy`
= note: the `Copy` trait is required because this value will be copied for each element of the array
Desired output
error[E0277]: the trait bound `String: Copy` is not satisfied
--> src/main.rs:2:14
|
2 | let x = [None::<String>; 10];
| ^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
|
= note: required for `Option<String>` to implement `Copy`
= note: the `Copy` trait is required because this value will be copied for each element of the array
= help: consider creating a new `const` item and initializing it with the value to be used in the repeat position, like `const VAL: Type = value;` and `let x = [VAL; 42];`
Rationale and extra context
I'm basing this suggestion on two things. One, that if you follow it, the code compiles:
fn main() {
const NONE: Option<String> = None;
let x = [NONE; 10];
}
and two, that the diagnostic help you get when you try to use a const fn
in the repeat position suggests something very similar, see "other cases." It would require the compiler to know that a value that is attempted to be repeated is const
able though, which I don't know whether it can, but I figured I'd suggest this, and you can reject it if it isn't possible to do.
Alternatively, the help text could say something like "if the value can be made const
, consider creating [...]"
Other cases
I was inspired to make this issue based on the output you get when you try to use a const fn
as an array initializer. For instance, the code
fn main() {
let x = [none::<String>(); 10];
}
const fn none<T>() -> Option<T> {
None
}
produces the output
error[E0277]: the trait bound `String: Copy` is not satisfied
--> src/main.rs:2:14
|
2 | let x = [none::<String>(); 10];
| ^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String`
|
= note: required for `Option<String>` to implement `Copy`
= note: the `Copy` trait is required because this value will be copied for each element of the array
= help: consider creating a new `const` item and initializing it with the result of the function call to be used in the repeat position, like `const VAL: Type = const_fn();` and `let x = [VAL; 42];`
Anything else?
No response