如何克隆包含“Rc<Fn(T)>”的结构体?

6

我想定义一个类型,包括 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

如何改正我的代码?

1
#[derive(Clone)] 适用于简单情况,但并非所有情况都适用。需要手动实现 Clone - bluss
@bluss 已经起作用,谢谢。 - uwu
1个回答

4
问题在于#[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(),
        }
    }
}

2
怎么还没有人回答这个问题?快!快! - DK.
没错,就是这样 :) 我会删除我的。 - Vladimir Matveev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接