documentation of the Clone
trait表示"如果所有字段都是Clone
,则此特性可用于#[derive]
."我正在处理这样一种情况,即所有字段are和Clone
都不起作用,但派生Clone
不起作用.
请考虑以下简化的示例(Playground link):
use std::fmt;
use std::rc::Rc;
trait Printer: Clone {
fn print(&self) -> ();
}
#[derive(Clone)]
struct ClosurePrinter<T: fmt::Display> {
get_value: Rc<dyn Fn() ->T>,
}
impl<T: fmt::Display> ClosurePrinter<T> {
pub fn new(get_value: Rc<dyn Fn() -> T>) -> ClosurePrinter<T> {
ClosurePrinter { get_value }
}
}
impl<T: fmt::Display> Printer for ClosurePrinter<T> {
fn print(&self) -> () {
println!("{}", (self.get_value)())
}
}
struct ClosurePrinter
只有一个字段get_value: Rc<dyn Fn() -> T>
.Rc
等于Clone
,所以我假设get_value
等于Clone
.然而,编译器坚持认为T
也必须是Clone
:
error[E0277]: the trait bound `T: Clone` is not satisfied
--> src/lib.rs:19:23
|
19 | impl<T: fmt::Display> Printer for ClosurePrinter<T> {
| ^^^^^^^ the trait `Clone` is not implemented for `T`
|
note: required because of the requirements on the impl of `Clone` for `ClosurePrinter<T>`
--> src/lib.rs:8:10
|
8 | #[derive(Clone)]
| ^^^^^
note: required by a bound in `Printer`
--> src/lib.rs:4:16
|
4 | trait Printer: Clone {
| ^^^^^ required by this bound in `Printer`
= note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider further restricting this bound
|
19 | impl<T: fmt::Display + std::clone::Clone> Printer for ClosurePrinter<T> {
| +++++++++++++++++++
为什么编译器坚持T
必须是Clone
?