编译器强迫我实现特征方法,但是对于我的类型,方法上的`Self`特征约束永远不会满足

问题描述 投票:10回答:1

我有一个特质Foo。我想强制实现者定义一个方法,如果这些实现者实现另一个特征(在本例中为Clone)。我的想法(Playground):

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提供一个definitoin?特别是,如果我试图提供一个定义(Playground):

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!()作为正文来定义一堆方法。)

为什么编译器强迫我提供方法定义?我可以以某种方式解决这个问题吗?

rust traits
1个回答
12
投票

特征的所有实现者都需要实现没有默认实现的所有方法。具有定义的界面是特征的重点。向方法添加特征边界不会改变有关此规则的任何内容。

这就是language reference在这个话题上所说的:

特征实现必须定义由实现的特征声明的所有非默认关联项,可以重新定义由实现的特征定义的默认关联项,并且不能定义任何其他项。

这也意味着在特征上的方法声明中绑定在Self上的特征在功能上等同于声明超级特征,除了特征只能在声明边界的方法中使用。

显而易见的解决方法是为对Self有额外要求的方法定义一个单独的特征:

trait FooExt: Foo + Clone {
    fn foo(&self);
}

您现在可以为所有类型实现Foo,并为FooExt类型实现Clone

根据评论中的要求更新:有一个GitHub issue discussing whether it should be allowed to implement methods with unsatisfiable trait bounds without the method body,所以至少可以删除{ unimplemted()! }部分。截至2019年4月,这个讨论还没有得出任何结论,甚至没有解决实现不可赎回方法的确切语法。

© www.soinside.com 2019 - 2024. All rights reserved.