Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone the struct include `Rc<Fn(T)>`?

Tags:

rust

I want define a type, include Rc<Fn(T)>, T not required Clone trait, example code:

use std::rc::Rc;


struct X;

#[derive(Clone)]
struct Test<T> {
    a: Rc<Fn(T)>
}


fn main() {
    let t: Test<X> = Test {
        a: Rc::new(|x| {})
    };
    let a = t.clone();
}

can't complie, error message is:

test.rs:16:15: 16:22 note: the method `clone` exists but the following trait bounds were not satisfied: `X : core::clone::Clone`, `X : core::clone::Clone`
test.rs:16:15: 16:22 help: items from traits can only be used if the trait is implemented and in scope; the following trait defines an item `clone`, perhaps you need to implement it:
test.rs:16:15: 16:22 help: candidate #1: `core::clone::Clone`
error: aborting due to previous error

How to correct my code?

like image 290
uwu Avatar asked Oct 20 '22 06:10

uwu


1 Answers

The problem is that #[derive(Clone)] is rather stupid. As part of its expansion, it adds a Clone constraint to all generic type parameters, whether or not it actually needs such a constraint.

As such, you need to implement Clone manually, like so:

struct Test<T> {
    a: Rc<Fn(T)>
}

impl<T> Clone for Test<T> {
    fn clone(&self) -> Self {
        Test {
            a: self.a.clone(),
        }
    }
}
like image 57
DK. Avatar answered Oct 21 '22 22:10

DK.