gpt4 book ai didi

rust - 如何克隆 struct include `Rc` ?

转载 作者:行者123 更新时间:2023-11-29 07:51:27 25 4
gpt4 key购买 nike

我想定义一个类型,包括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 约束,无论它是否真的需要这样的约束。

因此,您需要手动实现Clone,如下所示:

struct Test<T> {
a: Rc<Fn(T)>
}

impl<T> Clone for Test<T> {
fn clone(&self) -> Self {
Test {
a: self.a.clone(),
}
}
}

关于rust - 如何克隆 struct include `Rc<Fn(T)>` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31676504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com