为什么必须冗余指定指针特征边界?

Dan*_*n R 5 rust

考虑以下情况,有两个Traits。第一个Trait用于指针类型,第二个Trait用于常规对象。第二个特征有一个HRTB,因此任何对实现第二个特征的类型的引用都必须实现第一个特征:

pub trait PtrTrait {}

pub trait RegTrait
where
    for<'a> &'a Self: PtrTrait,
{
}
Run Code Online (Sandbox Code Playgroud)

是的,这确实有效!在下文中,如果impl不包含第一个泛型,编译器会抱怨:

pub struct S();

// Note, this impl IS needed for the next impl to compile.
impl<'a> PtrTrait for &'a S {}

impl RegTrait for S {}
Run Code Online (Sandbox Code Playgroud)

问题是编译器在编写泛型函数时似乎没有记住这一点。以下函数定义无法编译:

pub fn bar<T: RegTrait>() {}
Run Code Online (Sandbox Code Playgroud)

错误来自rustc简单地说,for<'a> &'a T: PtrTrait该类型不满足trait bound &'a T。如果我where在函数中添加一个子句:

where for<'a> &'a T: PtrTrait
Run Code Online (Sandbox Code Playgroud)

那么它就起作用了——但是如果它已经是对特征本身的一个约束,为什么还需要它呢?

操场