考虑这两个特征:
pub trait Foo {
fn new(arg: u32) -> Self;
}
pub trait Bar<P>: Foo {
fn with_parameter(arg: u32, parameter: P) -> Self;
}
我想添加毯子暗示:
impl<T: Bar<P>, P: Default> Foo for T {
fn new(arg: u32) -> Self {
Self::with_parameter(arg, P::default())
}
}
但我收到编译器错误:
error[E0207]: the type parameter `P` is not constrained by the impl trait, self type, or predicates
--> src/lib.rs:9:17
|
9 | impl<T: Bar<P>, P: Default> Foo for T {
| ^ unconstrained type parameter
我认为我得到这个错误是因为我违反了特质一致性规则,但我不明白这会打破什么规则。为什么不允许这种模式?而且,更重要的是,我能否在不出现错误的情况下实现我想要的目标?
问题是单一类型可以实现Bar<P>
对于多个值P
。如果你有一个结构Baz
实施的Bar<i32>
and Bar<String>
,哪种类型应该Foo::new
用于P
?
唯一的解决方案是确保单一类型不能实现Bar
不止一次(如果这不是您想要的,那么您的设计就有缺陷!)。为此,我们必须更换P
具有关联类型的类型参数。
pub trait Bar: Foo {
type Parameter;
fn with_parameter(arg: u32, parameter: Self::Parameter) -> Self;
}
impl<T> Foo for T
where
T: Bar,
T::Parameter: Default,
{
fn new(arg: u32) -> Self {
Self::with_parameter(arg, T::Parameter::default())
}
}
一个实现Bar
看起来像这样:
struct Baz;
impl Bar for Baz {
type Parameter = i32;
fn with_parameter(arg: u32, parameter: Self::Parameter) -> Self {
unimplemented!()
}
}
也可以看看:
- 为什么在为闭包特征 (Fn) 创建总体实现时会出现“类型参数不受约束”? https://stackoverflow.com/q/37377490/155423
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)