Rust 如何克隆结构include`Rc<;Fn(T)>;`?
我想定义一个类型,包括Rust 如何克隆结构include`Rc<;Fn(T)>;`?,rust,Rust,我想定义一个类型,包括Rc,T非必需克隆特征,示例代码: 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(); } 如何更正我的代码?问题是#[派生(克
Rc
,T
非必需克隆
特征,示例代码:
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();
}
如何更正我的代码?问题是#[派生(克隆)]
相当愚蠢。作为扩展的一部分,它向所有泛型类型参数添加了一个Clone
约束,不管它是否实际需要这样的约束
因此,您需要手动实现Clone
,如下所示:
struct测试{
a:Rc
}
用于测试的impl克隆{
fn克隆(&self)->self{
试验{
a:self.a.clone(),
}
}
}
#[派生(克隆)]
适用于简单的情况,但并不适用于所有情况。手动实现Clone
。@bluss它成功了,谢谢“怎么还没有人回答这个问题?快!快!”对,它就是这样工作的:)我会删除我的。
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