Generic 101 question... i can make a generic for just number

I have this code

struct MinMax {
    min: f64,
    max: f64
}

impl MinMax {
    pub fn middle(&self) -> f64 {
        (self.min + self.max) / 2.0
    }
}

I'd like to make it more generic so as to be able to create it for i32, i64, f32, f64 and usize

struct MinMax<T> {
    min: T,
    max: T
}

impl<T> MinMax<T> {
    pub fn middle(&self) -> T {
        (self.min + self.max) / 2
    }
}

// CLIPPY OUTPUT
error[E0369]: cannot add `T` to `T`
  --> src\...\maths.rs:57:19
   |
57 |         (self.min + self.max) / 2
   |          -------- ^ -------- T
   |          |
   |          T
   |
help: consider restricting type parameter `T`
   |
55 | impl<T: std::ops::Add> MinMax<T> {
   |       +++++++++++++++

following the instruction does not work :frowning:

error[E0369]: cannot divide `<T as std::ops::Add>::Output` by `{integer}`
  --> src\...\maths.rs:57:31
   |
57 |         (self.min + self.max) / 2
   |         --------------------- ^ - {integer}
   |         |
   |         <T as std::ops::Add>::Output
   |
help: consider further restricting the associated type
   |
56 |     pub fn middle(&self) -> T where <T as std::ops::Add>::Output: std::ops::Div<i32> {

I can go one, but i don't think this is the solution...

You could do something like this.

Or perhaps this is adequate for you.

...or this one.

3 Likes

I guess i wasn't far off.. I need to read more about generics, it really simplifies stuf.. thanks

fyi, I went for the third solution (the let two = T::one() + T::one(); through me off, I dn't know why

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.