[英]Why is the failure::Fail trait bound not satisfied by my Result type alias?
[英]Compiler forces me to implement trait method but the `Self` trait bound on method is never satisfied for my type
我有一个特质Foo
。 我想强制实现者定义一个方法, 如果这些实现者实现另一个特征(在这个例子中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
提供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!()
的方法unreachable!()
作为正文。)
为什么编译器强迫我提供方法定义? 我可以以某种方式解决这个问题吗?
特征的所有实现者都需要实现没有默认实现的所有方法。 具有定义的界面是特征的重点。 向方法添加特征边界不会改变有关此规则的任何内容。
这是语言参考在该主题上所说的内容:
特征实现必须定义由实现的特征声明的所有非默认关联项,可以重新定义由实现的特征定义的默认关联项,并且不能定义任何其他项。
这也意味着在特征上的方法声明中绑定Self
的特征在功能上等同于声明超级特征,除了特征只能在声明边界的方法中使用。
显而易见的解决方法是为对Self
有额外要求的方法定义一个单独的特征:
trait FooExt: Foo + Clone {
fn foo(&self);
}
您现在可以为所有类型实现Foo
,而对于Clone
类型则可以实现FooExt
。
根据评论中的要求更新 :有一个GitHub问题,讨论是否应该允许在没有方法体的情况下实现具有不可满足的特征边界的方法 ,所以至少{ unimplemted()! }
{ unimplemted()! }
部分可能会被丢弃。 截至2019年4月,这个讨论还没有得出任何结论,甚至没有解决实现不可赎回方法的确切语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.