-
-
Notifications
You must be signed in to change notification settings - Fork 15k
Unintentionally cloning references can lead to confusing borrow checker errors #48677
Copy link
Copy link
Closed
Labels
A-borrow-checkerArea: The borrow checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.Diagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.
Description
Metadata
Metadata
Assignees
Labels
A-borrow-checkerArea: The borrow checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.Category: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.Diagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: Confusing error or lint; hard to understand for new users.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.Relevant to the compiler team, which will review and decide on the PR/issue.
Type
Fields
Give feedbackNo fields configured for issues without a type.
(Note from pnkfelix: I have updated the example to continue illustrating the issue even in the presence of NLL.)
This issue is a result of all references implementing Clone. The following code will not compile:
producing the misleading error message:
Because Clone is not a trait bound on T, where you'd expect
v.clone()to return a cloned T it's actually returning a cloned &T. The type ofcloned_itemsis inferred to beVec<&T>, and the lifetime of thelistimmutable borrow is extended to the lifetime ofcloned_items. This is hard to figure out from the error message. The solution is to add Clone as a trait bound to T. The following code builds:If you give cloned_items an explicit type
it gives an error that more clearly explains what you're doing wrong:
I'm not sure what my proposed fix would be. I don't know if there are any use cases for explicitly cloning a reference. Ideally you'd get a warning on cloning a reference to a type that doesn't implement Clone.