Rollup merge of #81503 - henryboisdequin:fix-const-fn-arr-err-msg, r=estebank
Suggest to create a new `const` item if the `fn` in the array is a `const fn` Fixes #73734. If the `fn` in the array repeat expression is a `const fn`, suggest creating a new `const` item. On nightly, suggest creating an inline `const` block. This PR also removes the `suggest_const_in_array_repeat_expressions` as it is no longer necessary. Example: ```rust fn main() { // Should not compile but hint to create a new const item (stable) or an inline const block (nightly) let strings: [String; 5] = [String::new(); 5]; println!("{:?}", strings); } ``` Gives this error: ``` error[E0277]: the trait bound `std::string::String: std::marker::Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:3:32 | 2 | let strings: [String; 5] = [String::new(); 5]; | ^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `String` | = note: the `Copy` trait is required because the repeated element will be copied ``` With this change, this is the error message: ``` error[E0277]: the trait bound `String: Copy` is not satisfied --> $DIR/const-fn-in-vec.rs:3:32 | LL | let strings: [String; 5] = [String::new(); 5]; | ^^^^^^^^^^^^^^^^^^ the trait `Copy` is not implemented for `String` | = help: moving the function call to a new `const` item will resolve the error ```
This commit is contained in:
commit
f02f7b05b2
8 changed files with 90 additions and 4 deletions
|
@ -1881,10 +1881,26 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
|
|||
ObligationCauseCode::Coercion { source: _, target } => {
|
||||
err.note(&format!("required by cast to type `{}`", self.ty_to_string(target)));
|
||||
}
|
||||
ObligationCauseCode::RepeatVec => {
|
||||
ObligationCauseCode::RepeatVec(is_const_fn) => {
|
||||
err.note(
|
||||
"the `Copy` trait is required because the repeated element will be copied",
|
||||
);
|
||||
|
||||
if is_const_fn {
|
||||
err.help(
|
||||
"consider creating a new `const` item and initializing 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];`",
|
||||
);
|
||||
}
|
||||
|
||||
if self.tcx.sess.is_nightly_build() && is_const_fn {
|
||||
err.help(
|
||||
"create an inline `const` block, see PR \
|
||||
#2920 <https://github.com/rust-lang/rfcs/pull/2920> \
|
||||
for more information",
|
||||
);
|
||||
}
|
||||
}
|
||||
ObligationCauseCode::VariableType(hir_id) => {
|
||||
let parent_node = self.tcx.hir().get_parent_node(hir_id);
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue