简体   繁体   中英

How do I require that a generic type supports numeric operations?

I have a struct (and some methods) like this:

pub struct Foo<T> where T:Ord+Add+Sub {
    bar: T,
    baz: T,
    // ...
}

I need to do some numeric operations (addition, subtraction etc) and store the results. The documentation states that the result in the Sub or Add traits may be yet another type.

If you look at the Add trait you will see:

pub trait Add<RHS = Self> {
    type Output;
    fn add(self, rhs: RHS) -> Self::Output;
}

This is the flexibility required to specify the result type depending on both the Left and Right arguments to + .

If you wish to constrain your Foo<T> structure to T for which there exists a symmetric implementation of T which itself returns T , you can do so in the where clause:

  • to require that T can be added to T , T must implement Add<T> (which, since RHS defaults to Self , is the same as implementing Add )
  • to require that the result be T , T must implement Add<Output = T> (the associated type syntax)

A similar principle applies to Sub , giving:

struct Foo<T>
    where T: Ord + Add<Output = T> + Sub<Output = T>
{
    ...
}

I don't know what you mean by "numeric type", but this is how you constrain the type such that addition and subtraction yield T :

pub struct Foo<T> where T: Ord+Add<Output=T>+Sub<Output=T> {
    ...
}

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