我想定义一个类型,包括 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
如何改正我的代码?
#[derive(Clone)]
适用于简单情况,但并非所有情况都适用。需要手动实现Clone
。 - bluss