我有一个特质Foo
。我想强迫实现者定义一个方法,if这些实现者实现了另一个特征(Clone
在此示例中)。我的想法 (操场):
trait Foo {
// Note: in my real application, the trait has other methods as well,
// so I can't simply add `Clone` as super trait
fn foo(&self)
where
Self: Clone;
}
struct NoClone;
impl Foo for NoClone {}
可悲的是,这会导致:
error[E0046]: not all trait items implemented, missing: `foo`
--> src/lib.rs:8:1
|
2 | / fn foo(&self)
3 | | where
4 | | Self: Clone;
| |____________________- `foo` from trait
...
8 | impl Foo for NoClone {}
| ^^^^^^^^^^^^^^^^^^^^ missing `foo` in implementation
我不明白这个错误:编译器清楚地知道NoClone
不执行Clone
,那么为什么我需要提供定义foo
?特别是,如果我尝试提供一个定义(操场):
impl Foo for NoClone {
fn foo(&self)
where
Self: Clone
{
unreachable!()
}
}
我收到错误:
error[E0277]: the trait bound `NoClone: std::clone::Clone` is not satisfied
--> src/lib.rs:9:5
|
9 | / fn foo(&self)
10 | | where
11 | | Self: Clone
12 | | {
13 | | unreachable!()
14 | | }
| |_____^ the trait `std::clone::Clone` is not implemented for `NoClone`
|
= help: see issue #48214
= help: add #![feature(trivial_bounds)] to the crate attributes to enable
所以编译器肯定知道。 (仅供参考:与#![feature(trivial_bounds)]
它可以编译,但我不想定义一堆方法unreachable!()
作为身体。)
为什么编译器强制我提供方法定义?我可以以某种方式解决这个问题吗?