相关疑难解决方法(0)

为什么我不能在带有类型参数的特征上添加毯子impl?

考虑以下两个特征:

pub trait Foo {
    fn new(arg: u32) -> Self;
}

pub trait Bar<P>: Foo {
    fn with_parameter(arg: u32, parameter: P) -> Self;
}
Run Code Online (Sandbox Code Playgroud)

我想添加毯子impl:

impl<T: Bar<P>, P: Default> Foo for T {
    fn new(arg: u32) -> Self {
        Self::with_parameter(arg, P::default())
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了编译器错误:

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
Run Code Online (Sandbox Code Playgroud)

我想我得到了这个错误,因为我违反了特质一致性规则,但我不明白究竟会破坏什么规则.为什么不允许这种模式?而且,更重要的是,我可以实现我想要的而不会出错吗?

generics traits type-parameter rust

7
推荐指数
2
解决办法
479
查看次数

标签 统计

generics ×1

rust ×1

traits ×1

type-parameter ×1