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?
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(),
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With