如何将 Sized 超级特征添加到 Rust 特征?

How to add a Sized supertrait to a Rust trait?

this issue page for Rust处,它给出了core::num::bignum::FullOps的以下示例代码:

pub trait FullOps {
    ...
    fn full_mul(self, other: Self, carry: Self) -> (Self /*carry*/, Self);
    ...
}

然后它说:

Here the function full_mul returns a (Self, Self) tuple, which is only well-formed when the Self-type is Sized - for that and other reasons, the trait only makes sense when Self is Sized. The solution in this case and most others is to add the missing Sized supertrait.

如何添加缺失的 Sized 超特质?

很简单:将第一行改为:

pub trait FullOps : Sized {

Playground link

一个 "super trait" 只是一个界限,真的。

您可以在特征级别或方法级别设置界限。这里建议放在trait level:

pub trait FullOps: Sized {
    fn full_mul(self, other: Self, carry: Self) -> (Self, Self);
}

另一个解决方案是将它放在方法级别:

pub trait FullOps {
    fn full_mul(self, other: Self, carry: Self) -> (Self, Self)
        where Self: Sized;
}