Rfcs: Make Clone a lang-item and implement it for closures whose members are all Clone

Created on 14 Nov 2015  路  8Comments  路  Source: rust-lang/rfcs

moved from rust-lang/rust#23501

T-lang T-libs

Most helpful comment

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)?

All 8 comments

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:

  • Iterator ergonomics - being able to clone Iterators with some F: Fn + Clone field
  • real-time thread synchronisation - being able to clone a F: Fn(&mut State) + Clone and send it to multiple real-time threads across via channels without requiring Arc

Not 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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

torkleyy picture torkleyy  路  3Comments

mqudsi picture mqudsi  路  3Comments

yongqli picture yongqli  路  3Comments

camden-smallwood-zz picture camden-smallwood-zz  路  3Comments

silversolver1 picture silversolver1  路  3Comments