Subtraction in a generic code (goal is performance)

I'm trying to comprehend what would be the correct implementation for the following code:

use std::ops::Sub;
use std::cmp::min;

struct Pair<Value> {
    a: Vec<Value>,
    b: Vec<Value>,
    c: Vec<Value>,
}

impl<'a, Value> Pair<Value>
where
    Self: 'a,
    Value: Ord + Clone + Sub<&'a Value, Output = Value>,
{
    fn min(&self, idx: usize) -> &Value {
        min(&self.a[idx], &self.b[idx])
    }

    fn gap(&'a self, idx: usize) -> Value {
        self.b[idx].clone() - self.min(idx)
    }
}

(Playground)

I just have some inner feeling that I'm misusing Rust here ))
, because for i32 code looks like here:

impl Pair<i32> {
    fn min(&self, idx: usize) -> &i32 {
        min(&self.a[idx], &self.b[idx])
    }

    fn gap(&self, idx: usize) -> i32 {
        self.b[idx] - self.min(idx)
    }
}

I mostly care about gap function, lifetimes and cloning as that would be the part of code related to intensive computations. In practice Value can be represented by complex structures, so Copy trait is not an option here.

What you want is a higher-ranked bound, e.g. [playground]

impl<Value> Pair<Value>
where
    Value: Ord,
    for<'a> &'a Value: Sub<&'a Value, Output = Value>,
{
    fn gap(&self, idx: usize) -> Value {
        &self.b[idx] - self.min(idx)
    }
}

This is how you state that you want &Value - &Value to work.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.