moved from rust-lang/rust#23501
Could this be implemented using default impls of Clone and Copy? I know that would be a pretty serious breaking change, because there could be types that are only sound because they don't implement Clone. But in principle, wouldn't closures be Clone if their environment is Clone if that were the case (or do default impls not apply to closures)?
This is also needed to fix rust-lang/rust#28229
Just thought I'd :+1: this and mention a couple use-cases I come across quite frequently:
F: Fn + Clone fieldF: Fn(&mut State) + Clone and send it to multiple real-time threads across via channels without requiring ArcNot just closures. Functions and arrays would be great as well.
Meet this same issue, here is an example:
#[derive(Debug)]
struct Take(String);
fn make<F>(func: F) -> Box<Fn(&str) -> Take>
where F: FnOnce(String) -> Take + Copy + 'static
{
Box::new(move |s| {
func(s.to_string())
})
}
fn main() {
let m = make(|s|Take(s));
println!("{:?}", m("abc"));
}
should compile.
I've started hitting this a lot, mostly in the "iterator ergonomics" that @mitchmindtree mentioned. I'm not sure why Clone needs to be a lang item (maybe there's something I'm missing), but having appropriate closures implement Clone sure would be convenient.
Since Clone was made a lang item in https://github.com/rust-lang/rust/pull/43690, I've written this up as https://github.com/rust-lang/rfcs/pull/2132.
Since the RFC was accepted, closing in favour of the tracking issue https://github.com/rust-lang/rust/issues/44490
Most helpful comment
Could this be implemented using default impls of
CloneandCopy? I know that would be a pretty serious breaking change, because there could be types that are only sound because they don't implementClone. But in principle, wouldn't closures beCloneif their environment isCloneif that were the case (or do default impls not apply to closures)?