我想要定义一个类型,包括Rc<Fn(T)>
,T
不必需的Clone
特征,示例代码:
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();
}
无法编译,错误信息是:
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
如何更正我的代码?
答案 0 :(得分:3)
问题在于#[derive(Clone)]
相当愚蠢。作为其扩展的一部分,它会为所有泛型类型参数添加Clone
约束,无论它是否确实需要这样的约束。
因此,您需要手动实施Clone
,如下所示:
struct Test<T> {
a: Rc<Fn(T)>
}
impl<T> Clone for Test<T> {
fn clone(&self) -> Self {
Test {
a: self.a.clone(),
}
}
}