简体   繁体   中英

How to add a Sized supertrait to a Rust trait?

At this issue page for Rust , it gives the following example code for core::num::bignum::FullOps :

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

Then it says that:

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.

How does one add the missing Sized supertrait?

A "super trait" is just a bound, really.

You can place a bound either at trait level or method level. Here, you are advised to place it at trait level:

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

The other solution would be to place it at method level:

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

It's quite simple: change the first line to:

pub trait FullOps : Sized {

Playground link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM