- Feature Name:
copy_closures
- Start Date: 2017-08-27
- RFC PR: rust-lang/rfcs#2132
- Rust Issue: rust-lang/rust#44490
Summary
ImplementClone
and Copy
for closures where possible:
Motivation
Idiomatic Rust often includes liberal use of closures. Many APIs have combinator functions which wrap closures to provide additionalIterator
and Future
traits).
However, closures are unique,Copy
or Clone
. This makes using closures unergonomic and limits their usability. Functions which takeIterator
or Future
combinators, or other closure-based types by-value are impossible to call
One current workaround is to use the coercion from non-capturing closures to fn
pointers, but this introduces unnecessary dynamic
This RFC solves this issue by implementingCopy
and Clone
traits on closures where possible.
Guide-level explanation
If a non-move
closure doesn't mutate captured variables,Copy
and Clone
:
Non-move
closures which mutate captured variablesCopy
nor Clone
:
move
closures are only Copy
or Clone
if the values they capture are Copy
or Clone
:
Reference-level explanation
Closures are internally representedmove
or non-move
closures). A closure type implementsClone
or Copy
if and only if the all values in the closure's internal representationClone
or Copy
:
-
Non-mutating non-
move
closures only contain含むimmutable不変のreferences参照(which areCopy + Clone
), so these closures areCopy + Clone
. -
Mutating non-
move
closures contain含むmutable references,参照which are neitherCopy
norClone
, so these closures are neitherCopy
norClone
. -
move
closures contain含むvalues moved out of the enclosing囲うscope, so these closures areClone
orCopy
if and only if all of the values they capture areClone
orCopy
.
The internal implementationClone
for non-Copy
closures will resemble the basic implementationderive
, but the orderClone
d will remain unspecified.
Drawbacks
This feature increasesCopy
or Clone
.
However, this can be mitigated through error messages which point to the specificCopy
or Clone
bounds.
Rationale and Alternatives
It would be possible to implementClone
or Copy
for a more minimal setmove
closures, or non-mutating closures. This could make it easier to reason about exactlyCopy
or Clone
, but this would come at the cost of greatly decreased functionality.
Unresolved questions
- How can we provide high-quality, tailored error messages to indicate指し示すwhy a closure isn't
Copy
orClone
?